Invert Binary Tree

Invert a binary tree.

Have you met this question in a real interview? Yes

Example

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

Challenge

Do it in recursion is acceptable, can you do it without recursion?

Solution

public class Solution {
    /**
     * Recursion 
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void invertBinaryTree(TreeNode root) {
        if(root == null)
            return;

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertBinaryTree(root.left);
        invertBinaryTree(root.right);
    }

    /**
     * Non-recursion, it likes tree preorder traversal 
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void invertBinaryTree(TreeNode root) {
        if(root == null)
            return;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
            if(node.right != null)
                stack.push(node.right);
            if(node.left != null)
                stack.push(node.left);
        }
    }        
}

results matching ""

    No results matching ""