538. 把二叉搜索树转换为累加树
Tag Tree
Difficulty Easy
Link https://leetcode-cn.com/problems/convert-bst-to-greater-tree/
二叉搜索树的特点是节点的左子节点的值小于等于它的值,右子节点的值大于等于它的值,现在要使得每个节点加上比它大的所有值。
我们知道中序遍历的结果就是把二叉搜索树从小到大排列,那么我们可以从最大的节点开始,不断往前,每次都加上后面节点的值。
class Solution {
public TreeNode convertBST(TreeNode root) {
if (root == null) {
return root;
}
List<TreeNode> mList = new ArrayList<>();
inOrder(root, mList);
int index = mList.size() - 1;
TreeNode next = mList.get(index);
while (index > 0) {
index--;
TreeNode cur = mList.get(index);
cur.val += next.val;
next = cur;
}
return root;
}
public void inOrder(TreeNode root, List<TreeNode> mList) {
if (root == null) {
return;
}
inOrder(root.left, mList);
mList.add(root);
inOrder(root.right, mList);
}
}
还有一种方法是反向的中序遍历,这种方式非常巧妙,采用右根左的方式,先搜索到树的最大值,然后在不断返回的过程中,获取比当前节点大的所有值的和。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int sum = 0;
public TreeNode convertBST(TreeNode root) {
if (root != null) {
convertBST(root.right);
sum += root.val;
root.val = sum;
convertBST(root.left);
}
return root;
}
}