226. Invert Binary Tree

Link

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Solution

invert 上就是把左右子樹swap,然後左右子樹的子樹也要做一樣的事情 and so on。

Recursion

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

Iteration

 public TreeNode invertTree(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>(); //用queue也可以 沒差
        if(root == null) return null;
        
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop(); 
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
            if(node.left != null) stack.push(node.left);
            if(node.right != null) stack.push(node.right);
        }
        return root;
    }

Last updated

Was this helpful?