Java Solution using Stack


  • 1
    R
     class Solution {
        public void flatten(TreeNode root) {
            if(root == null) return;
        
            Stack<TreeNode> s = new Stack<TreeNode>();
        
            s.push(root);
            while(!s.empty()) {
                TreeNode curNode = s.pop();
            
                if(curNode.right != null) s.push(curNode.right);
                if(curNode.left != null) s.push(curNode.left);
            
                curNode.right = (s.empty()) ? null : s.peek();
                curNode.left = null;
            }
        }
    }

  • 0
    L
    public void flatten(TreeNode root) {
        if(root==null)
            return;
        Stack<TreeNode> s = new Stack<TreeNode>();
        TreeNode p = root;
        while(p!=null || !s.isEmpty()) {
            if(p.right != null)
                s.push(p.right);
            if(p.left != null){
                p.right = p.left;
                p.left = null;
            }else if(!s.isEmpty()) {
                TreeNode temp = s.pop();
                p.right = temp;
            }
            p = p.right;
        }
    }

Log in to reply
 

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