题目:
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:Input: The root of a Binary Search Tree like this: 5 / \ 2 13 Output: The root of a Greater Tree like this: 18 / \ 20 13
解释:
先中序遍历取出来,还原成一棵树的时候把加过的值替换上去(还原的时候从右边开始还原,中序遍历的时候从左边开始取)。
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
middle_list=[]
def middle(root):
if root==None:
return None
middle(root.left)
middle_list.append(root.val)
middle(root.right)
middle(root)
self.s=0
def middle2tree(root):
if root==None:
return None
middle2tree(root.right)
self.s+=middle_list.pop()
root.val=self.s
middle2tree(root.left)
middle2tree(root)
return root
其实用一遍遍历就可以了,但是要先遍历右子树再遍历左子树。
python代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.cur=0
def dfs(root):
if not root:
return
dfs(root.right)
self.cur+=root.val
root.val=self.cur
dfs(root.left)
dfs(root)
return root
c++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int cur=0;
TreeNode* convertBST(TreeNode* root) {
dfs(root);
return root;
}
void dfs(TreeNode* root)
{
if (!root)
return ;
dfs(root->right);
cur+=root->val;
root->val=cur;
dfs(root->left);
}
};
总结:
正如之前的一道题目,可以在遍历树的时候处理一些问题,不需要先把list写好再处理了。