题目链接:https://leetcode.cn/problems/convert-bst-to-greater-tree/
方法一 迭代
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
public TreeNode convertBST(TreeNode root) {
if (root == null) return root;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
int sum = 0;
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.push(cur);
cur = cur.right;
}
int size = stack.size();
cur = stack.pop();
sum += cur.val;
cur.val = sum;
cur = cur.left;
}
return root;
}
}
3 复杂度分析
时间复杂度:
空间复杂度:
4 涉及到知识点
5 总结
方法二 递归
1 方法思想
2 代码实现
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
if (root == null) return root;
convert(root);
return root;
}
public void convert(TreeNode root){
if (root == null) return;
convert(root.right);
sum += root.val;
root.val = sum;
convert(root.left);
}
}
3 复杂度分析
时间复杂度:
空间复杂度: