题目描述
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:
输入: 原始二叉搜索树:
5
/ \
2 13
输出: 转换为累加树:
18
/ \
20 13
思路
通过(右子树->根->左子树)进行遍历,可以得到一个降序排列,然后将这些值累加即可。
代码
package cn.com.sky.interview.algorithm.hot100;
/**
* @author sky
* @date 2020/7/29 7:52
*
* 把二叉搜索树转换为累加树
* question: https://leetcode-cn.com/problems/convert-bst-to-greater-tree/
*/
public class ConvertBstToGreaterTree538 {
int val = 0;
public TreeNode convertBST(TreeNode root) {
if (root == null) {
return null;
}
if (root.right != null) {
convertBST(root.right);
}
root.val += val;
val = root.val;
if (root.left != null) {
convertBST(root.left);
}
return root;
}
}