题目描述:
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}思路一:使用递归
用逆中序遍历“右根左”,降序遍历BST中的结点。
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
public void convert(TreeNode node)
{
if (node == null)
return;
convert(node.right);
node.val += sum;
sum = node.val;
convert(node.left);
}
}若不使用全局变量
class Solution {
public TreeNode convertBST(TreeNode root) {
dfs(root, 0);
return root;
}
public int dfs(TreeNode node, int val)
{
if (node == null)
return val;
int right = dfs(node.right, val);
node.val += right;
int left = dfs(node.left, node.val);
return left;
}
}思路二:使用迭代,栈
class Solution {
public TreeNode convertBST(TreeNode root) {
if (root == null)
return null;
int sum = 0;
Stack<TreeNode> stack = new Stack<>();
TreeNode currNode = root;
while (currNode != null || !stack.isEmpty())
{
while (currNode != null)
{
stack.push(currNode);
currNode = currNode.right;
}
currNode = stack.pop();
currNode.val += sum;
sum = currNode.val;
currNode = currNode.left;
}
return root;
}
}思路三:
Morris Traversal方法遍历二叉树(非递归,不用栈,O(1)空间)。
class Solution {
public TreeNode convertBST(TreeNode root) {
if (root == null)
return null;
int sum = 0;
TreeNode curr = root;
while (curr != null)
{
if (curr.right == null)
{
curr.val += sum;
sum = curr.val;
curr = curr.left;
}
else
{
TreeNode pre = curr.right;
while (pre.left != null && pre.left != curr)
pre = pre.left;
if (pre.left == null)
{
pre.left = curr;
curr = curr.right;
}
else
{
pre.left = null;
curr.val += sum;
sum = curr.val;
curr = curr.left;
}
}
}
return root;
}
}
本文介绍如何将二叉搜索树(BST)转换为大于等于树,通过三种方法实现:递归逆中序遍历、迭代使用栈以及Morris遍历。每种方法均有详细代码示例。

被折叠的 条评论
为什么被折叠?



