LeetCode 538----Convert BST to Greater Tree
2017-03-19 11:01
483 查看
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
算法分析:
用"中序遍历"的方式访问每个节点的值,并将该节点的值累加到一个 int sum 变量上,并用该 sum 变量更新该节点的值。要注意的是,此处的中序遍历是先遍历右子树,再访问根节点,然后再遍历左子树(因为 BST 根节点的值小于右子树所有节点的值,大于左子树所有节点的值)。
Java 算法实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { int sum=0; public TreeNode convertBST(TreeNode root) { sum=0; addSum(root); return root; } public void addSum(TreeNode root){ if(root!=null){ addSum(root.right); sum+=root.val; root.val=sum; addSum(root.left); } } }
相关文章推荐
- leetcode(538). Convert BST to Greater Tree
- leetcode(538):Convert BST to Greater Tree
- LeetCode-538 Convert BST to Greater Tree
- leetcode 538 Convert BST to Greater Tree C++
- LeetCode - 538 - Convert BST to Greater Tree
- Leetcode 538:Convert BST to Greater Tree
- LeetCode 538 Convert BST to Greater Tree(二叉树的右中左遍历)
- Convert BST to Greater Tree(leetcode)
- [LeetCode] Convert BST to Greater Tree 将二叉搜索树BST转为较大树
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- LeetCode Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- [538 Convert BST to Greater Tree]搜索二叉树的数值计算
- 538. Convert BST to Greater Tree
- 538. Convert BST to Greater Tree
- LeetCode Convert BST to Greater Tree