给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:
输入: 二叉搜索树:
5
/ \
2 13
输出: 转换为累加树:
18
/ \
20 13
解答:
遍历树并使用数组记录各个节点数字,然后再遍历树并通过比对数组中的元素更新节点值
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
static ArrayList<Integer> arrayList = new ArrayList<>();
public static void bst(TreeNode root) {
if (root == null){
return;
}
arrayList.add(root.val);
bst(root.left);
bst(root.right);
}
public static void bst_(TreeNode root){
if (root == null){
return;
}
int i = 0;
int m = root.val;
for (int num : arrayList){
if (m < num){
root.val = root.val + num;
}
}
bst_(root.left);
bst_(root.right);
}
public static TreeNode convertBST(TreeNode root) {
bst(root);
Collections.reverse(arrayList);
bst_(root);
arrayList.clear();
return root;
}
}
后来发现没用审题,题目中说这是BST查询二叉树(节点值有序排列),所以直接遍历右子树就可以知道大于各节点的所有值。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
bst(root);
return root;
}
public void bst(TreeNode root){
if (root == null) return;
bst(root.right);
sum = sum + root.val;
root.val = sum;
bst(root.left);
}
}