538 把二叉搜索树转换为累加树

本文最后更新于:2022年9月22日 晚上

给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

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

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

注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同

示例 1:

img

1
2
输入:[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:

1
2
输入:root = [0,null,1]
输出:[1,null,1]

示例 3:

1
2
输入:root = [1,0,2]
输出:[3,3,2]

示例 4:

1
2
输入:root = [3,2,4,1]
输出:[7,9,4,10]

提示:

  • 树中的节点数介于 0104 之间。
  • 每个节点的值介于 -104104 之间。
  • 树中的所有值 互不相同
  • 给定的树为二叉搜索树。

Solution

参考 代码随想录

  • 递归法
  • 其实这就是一棵树,是一个有序数组[2, 5, 13],求从后到前的累加数组,也就是[20, 18, 13]。
  • 反中序遍历
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
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
if (root == nullptr) return nullptr;
traversal(root);
return root;
}
private:
TreeNode* pre = new TreeNode(0);

void traversal(TreeNode* cur) {
if (cur == nullptr) return;
traversal(cur->right);
cur->val += pre->val;
pre = cur;
traversal(cur->left);
}
};
// @lc code=end
  • 迭代法,反中序遍历
  • 设置 pre 结点
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
if (root == nullptr) return root;
// 反中序遍历
stack<TreeNode *> stack;
TreeNode* cur = root;
TreeNode* pre = new TreeNode(0);
while (cur || !stack.empty()) {
while (cur) {
stack.push(cur);
cur = cur->right;
}

cur = stack.top();
stack.pop();
cur->val += pre->val;
pre = cur;

cur = cur->left;
}
return root;
}
};

java

  • 迭代法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public TreeNode convertBST(TreeNode root) {
if (root == null) {
return null;
}
TreeNode pre = new TreeNode(0);
TreeNode cur = root;
Stack<TreeNode> stack = new Stack<>();
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
cur = cur.right;
}
cur = stack.pop();
cur.val += pre.val;
pre = cur;
cur = cur.left;
}
return root;
}
}
  • 递归法
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
private int preSum = 0;
public TreeNode convertBST(TreeNode root) {
if (root != null) {
convertBST(root.right);
root.val += preSum;
preSum = root.val;
convertBST(root.left);
}
return root;
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!