Java Solution. Iterative Preorder DFS


  • 0
    A
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
        Stack<TreeNode> remainingTreeNode = new Stack<TreeNode>();
        TreeNode curNode = root;
        while(!remainingTreeNode.empty() || curNode != null) {
            while(curNode != null) {
                remainingTreeNode.push(curNode);
                TreeNode tempNode = curNode.left;
                curNode.left = curNode.right;
                curNode.right = tempNode;
                curNode = curNode.left;
            }
            curNode = remainingTreeNode.pop().right;
        }
        return root;
    }

Log in to reply
 

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