Java iteration solution, easy to understand


  • 0
    S
    public class Solution {
        public TreeNode convertBST(TreeNode root) {
            TreeNode res = root;
            Stack<TreeNode> stack = new Stack<>();
            TreeNode prev = null;
            while (root != null || !stack.isEmpty()) {
                while (root != null) {
                    stack.push(root);
                    root = root.right;
                }
                TreeNode cur = stack.pop();
                if (prev != null) cur.val += prev.val;
                prev = cur;
                root = cur.left;
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.