-
Notifications
You must be signed in to change notification settings - Fork 1
/
ConvertBstToGreaterTree.java
85 lines (76 loc) · 2.42 KB
/
ConvertBstToGreaterTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.hncboy;
/**
* @author hncboy
* @date 2021/12/4 13:33
* @description 538.把二叉搜索树转换为累加树
*
* 给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),
* 使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
* 提醒一下,二叉搜索树满足下列约束条件:
*
* 节点的左子树仅包含键 小于 节点键的节点。
* 节点的右子树仅包含键 大于 节点键的节点。
* 左右子树也必须是二叉搜索树。
* 注意:本题和 1038 {@link BinarySearchTreeToGreaterSumTree}: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同
*
* 示例 1:
* 输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
* 输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
*
* 示例 2:
* 输入:root = [0,null,1]
* 输出:[1,null,1]
* 示例 3:
*
* 输入:root = [1,0,2]
* 输出:[3,3,2]
*
* 示例 4:
* 输入:root = [3,2,4,1]
* 输出:[7,9,4,10]
*
* 提示:
* 树中的节点数介于 0 和 104 之间。
* 每个节点的值介于 -104 和 104 之间。
* 树中的所有值 互不相同 。
* 给定的树为二叉搜索树。
* 通过次数 117,188 提交次数 165,499
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class ConvertBstToGreaterTree {
public TreeNode convertBST(TreeNode root) {
dfs(root, 0);
return root;
}
/**
* 反中序遍历
*/
private int dfs(TreeNode root, int sum){
// sum 为所有比当前节点大的节点的和
if(root == null){
return sum;
}
// 先遍历右子树,累加右子树所有节点的值
root.val += dfs(root.right, sum);
// 再遍历左子树,将累加后的值给左子树节点
return dfs(root.left, root.val);
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}