Accept Java Solution Using stack


  • 0
    Y
    public class Solution {
        Stack<TreeNode> stack=new Stack<TreeNode>();
        public TreeNode convertBST(TreeNode root) {
            inorder(root,stack);
            int sum=0;
            while(!stack.isEmpty())
            {
                TreeNode current=stack.pop();
                int temp=current.val;
                current.val+=sum;
                sum=sum+temp;
            }
            return root;
        }
        public void inorder(TreeNode root,Stack<TreeNode> stack)
        {
            if(root==null)
            return;
            inorder(root.left,stack);
            stack.push(root);
            inorder(root.right,stack);
        }
    

    }


Log in to reply
 

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