给定二叉搜索树(BST),将其转换为更大的树,使原始BST上每个节点的值都更改为在原始树中大于等于该节点值得节点值之和(包括该节点)。
样例:
Given a binary search Tree `{5,2,13}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
思路
中序遍历,递归。
#ifndef C661_H
#define C661_H
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
class TreeNode{
public:
int val;
TreeNode *left, *right;
TreeNode(int val)
{
this->val = val;
this->left = this->right = NULL;
}
};
class Solution {
public:
/*
* @param root: the root of binary tree
* @return: the new root
*/
TreeNode * convertBST(TreeNode * root) {
// write your code here
if (root == NULL)
return NULL;
vector<int> v;
createVector(root, v);
int len = v.size();
for (int i = 0; i < len; ++i)
{
v[i] = accumulate(v.begin() + i, v.end(), 0);//累加得到从i位置到尾部的所有元素的和
}
pos = 0;
createTree(root, v);
return root;
}
//中序遍历并将节点的值存入v
void createVector(TreeNode *root, vector<int> &v)
{
if (root == NULL)
return;
createVector(root->left, v);
v.push_back(root->val);
createVector(root->right, v);
}
//中序遍历并将节点的值置为v[pos]
void createTree(TreeNode *root, vector<int> &v)
{
if (root == NULL)
return;
createTree(root->left, v);
root->val = v[pos++];
createTree(root->right, v);
}
int pos;
};
#endif