给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
class Solution(object):
def convertBST(self, root):
self.cur_sum=0
self.travel(root)
return root
def travel(self,root):
if not root:
return
if root.right:
self.travel(root.right)
root.val+=self.cur_sum
self.cur_sum=root.val
if root.left:
self.travel(root.left)
class Solution {
private:
stack<TreeNode*>s;
void inorderTravel(TreeNode* root){
if(!root)
return;
if(root->left)
inorderTravel(root->left);
s.push(root);
if(root->right)
inorderTravel(root->right);
}
public:
TreeNode* convertBST(TreeNode* root) {
if(!root)
return 0;
inorderTravel(root);
int sum=0;
while(!s.empty())
{
sum+=s.top()->val;
s.top()->val=sum;
s.pop();
}
return root;
}
};
class Solution {
// !!! 不太很优雅,但却让代码更容易理解!!!
private int rightSum = 0;
// 先将右子树转换为累加树;并记录右子树的累加和rightSum;
// 然后处理根节点,根节点的值 = 根节点值 + rightSum;
// 然后转化左子树
public TreeNode convertBST(TreeNode root) {
if(null == root){
return root;
}
convertBST(root.right);
root.val = root.val + rightSum;
rightSum = root.val;
convertBST(root.left);
return root;
}
}
class Solution {
// 先将右子树转换为累加树;并记录右子树的累加和rightSum;
// 然后处理根节点,根节点的值 = 根节点值 + rightSum;
// 然后转化左子树
public TreeNode convertBST(TreeNode root) {
convert(root, 0);
return root;
}
public int convert(TreeNode root, int rightSum){
if(null == root){
return rightSum;
}
rightSum = convert(root.right, rightSum);
root.val = root.val + rightSum;
rightSum = root.val;
rightSum = convert(root.left, rightSum);
return rightSum;
}
}