226. Invert Binary Tree

Solution1:递归 pre-order / 分治

Time Complexity: O(N) Space Complexity: O(N) 递归缓存

Solution2:Iterative pre-order

Time Complexity: O(N) Space Complexity: O(N)

Solution2:BFS

Time Complexity: O(N) Space Complexity: O(N)

Solution1 Code:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        
        TreeNode left_save = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(left_save);
        
        return root;
    }
}

Solution2 Code:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        
        Stack stack = new Stack();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            
            TreeNode left_save = cur.left;
            cur.left = cur.right;
            cur.right = left_save;
            
            if(cur.right != null) stack.push(cur.right);
            if(cur.left != null) stack.push(cur.left);
        }
        return root;
    }
}

Solution3 Code:

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        
        Queue queue = new LinkedList();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            
            TreeNode left_save = cur.left;
            cur.left = cur.right;
            cur.right = left_save;
            
            if(cur.right != null) queue.offer(cur.right);
            if(cur.left != null) queue.offer(cur.left);
        }
        return root;
    }
}

你可能感兴趣的:(226. Invert Binary Tree)