538. 把二叉搜索树转换为累加树

labuladong 题解思路

难度中等

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

  • 节点的左子树仅包含键 小于 节点键的节点。
  • 节点的右子树仅包含键 大于 节点键的节点。
  • 左右子树也必须是二叉搜索树。

注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同

 

示例 1:

 
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.cur_sum = 0
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:

        def dfs(root):
            if root == None:
                return None
            dfs(root.right)
            root.val = self.cur_sum+root.val
            self.cur_sum = root.val
            dfs(root.left)
            return root
        return dfs(root)

 

 
 
 
 1 class Solution {
 2     int sum = 0;
 3     public TreeNode convertBST(TreeNode root) {
 4         convert(root);
 5         return root;
 6     }
 7     public void convert(TreeNode root){
 8         if(root==null) return;
 9         convert(root.right);
10         root.val+=sum;
11         sum = root.val;
12         convert(root.left);
13     } 
14 }

 

 

 

 
posted @ 2017-10-26 10:04  乐乐章  阅读(137)  评论(0编辑  收藏  举报