1. 程式人生 > >538. Convert BST to Greater Tree(python+cpp)

538. Convert BST to Greater Tree(python+cpp)

題目:

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寫好再處理了。