首页 > 代码库 > LeetCode: Convert BST to Greater Tree

LeetCode: Convert BST to Greater Tree

利用好BST的特性,解起来并不难

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     private int sum = 0;
12     public TreeNode convertBST(TreeNode root) {
13         if (root == null) return null;
14         convertBST(root.right);
15         root.val += sum;
16         sum = root.val;
17         convertBST(root.left);
18         return root;
19     }
20 }

 

LeetCode: Convert BST to Greater Tree