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

题目描述

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

思路分析

中序遍历

参考代码

1
write your code here

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public TreeNode convertBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode pre = null;
        while (!stack.isEmpty() || cur != null) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.right;
            }
            TreeNode node = stack.pop();
            if (pre != null) {
                node.val += pre.val;
            }
            pre = node;
            cur = node.left;
        }
        return root;
    }
}
本文作者:
本文链接: https://hgnulb.github.io/blog/2023/08310769
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!