java - iterative and recursive solution


  • 0
    //recursive version
    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null)
                return root;
            TreeNode temp = root.right;
            root.right = invertTree(root.left);
            root.left = invertTree(temp);
            return root;
        }
    }
    //iterative solution
    
    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null)
                return root;
            Deque<TreeNode>nodeStack = new LinkedList<>();
            nodeStack.addLast(root);
            while(!nodeStack.isEmpty()){
                int size = nodeStack.size();
                while(size-- > 0){
                    TreeNode curNode = nodeStack.pop();
                    TreeNode temp = curNode.left;
                    curNode.left = curNode.right;
                    curNode.right = temp;
                    if(curNode.left != null){
                        nodeStack.addLast(curNode.left);
                    }
                    if(curNode.right != null){
                        nodeStack.addLast(curNode.right);
                    }
                }
            }
            return root;
        }
    }
    

Log in to reply
 

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