[LintCode] Invert Binary Tree

461 查看

Example

  1         1
 / \       / \
2   3  => 3   2
   /       \
  4         4
  

Solution

Recursion:

public class Solution {
    public void invertBinaryTree(TreeNode root) {
        if (root == null) return;
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        invertBinaryTree(root.left);
        invertBinaryTree(root.right);
        return;
    }
}

Queue/linkedlist:

用queue的方法要熟练掌握。

public class Solution {
    public void invertBinaryTree(TreeNode root) {
        if (root == null) return;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
            if (node.left != null) {
                queue.offer(node.left);
            }
            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return;
    }
}