LeetCode 题解系列(1038):从二叉搜索树到更大和树

题目描述:

给出二叉 搜索 树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。

解法一: 中序遍历

因为搜索二叉树的性质,所以可以使用先右、后中、再左的方式中序遍历二叉树,每次更新一个累加和,加到当前节点上。

时间复杂度: O(N); 辅助空间复杂度: O(N)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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 bstToGst(TreeNode root) {
if (root == null) {
return null;
}
bstToGst(root.right);
sum += root.val;
root.val = sum;
bstToGst(root.left);
return root;
}
}

LeetCode 题解系列(1038):从二叉搜索树到更大和树
http://example.com/2020/07/08/D-DataStructureAndAlgorithm/D-LeetCode/1038-BstToGst/
作者
ChenXi
发布于
2020年7月8日
许可协议