Easy understanding Java AC solution


  • 0
    U
    public class Solution {//a node's left node always exist, if a node is right node then the subtree rooted at that node will remain same stcture in the new structure.
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if(root==null)
            return null;
        Stack<TreeNode> stack= new Stack<TreeNode>();
        while(root!=null){
            stack.push(root);
            root=root.left;
        }
        root= stack.peek();
        while(!stack.empty()){
            TreeNode temp=stack.pop();
            if(stack.size()==0){
                 break;
            }
            temp.right=stack.peek();
            temp.left=stack.peek().right;
            if(stack.size()==1){
                TreeNode temp1=stack.pop();
                temp1.right=null;
                temp1.left=null;
                break;
            }
    
        }
        return root;
    }
    

    }


Log in to reply
 

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