Java实现-LeetCode-538-把二叉搜索树转换为累加树遍历树
目录
Java实现 LeetCode 538 把二叉搜索树转换为累加树(遍历树)
538. 把二叉搜索树转换为累加树
给定一个二叉搜索树(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 {
int num = 0;
public TreeNode convertBST(TreeNode root) {
if (root != null) {
//遍历右子树
convertBST(root.right);
//遍历顶点
root.val = root.val + num;
num = root.val;
//遍历左子树
convertBST(root.left);
return root;
}
return null;
}
}