538. Convert BST to Greater Tree
Leetcode TreeGiven 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
分析¶
首先想到的办法是直接根据题目的描述一步一步做。第一步,遍历整个二叉树得到节点。第二步,计算每个节点的值。第三步,遍历二叉树给节点赋值。
private int position;
private List<Integer> list;
public TreeNode convertBST(TreeNode root) {
list = new ArrayList<>();
position = 0;
inorderTraversal(root);
for (int i = list.size() - 2; i >= 0; i--) {
list.set(i, list.get(i) + list.get(i+1));
}
System.out.println(list);
inorderTraversalSet(root);
return root;
}
private void inorderTraversalSet(TreeNode root) {
if (root == null) return;
inorderTraversalSet(root.left);
root.val = list.get(position++);
inorderTraversalSet(root.right);
}
private void inorderTraversal(TreeNode root) {
if (root == null) return;
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
}
一般的中序遍历的结果是依次递增的序列,那么可不可以变成依次递减的序列,这样的话,就可以通过递归来一次性赋值了。答案是可以:通过交换访问左子节点和右子节点的顺序。
private int sum = 0;
public TreeNode convertBST(TreeNode root) {
if (root == null) return null;
convertBST(root.right);
sum += root.val;
root.val = sum;
convertBST(root.left);
return root;
}