[LeetCode 226] Invert Binary Tree

Invert a binary tree.

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

Solution:

1. recursion

2. Iterative+queue


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

public TreeNode invertTree(TreeNode root) {
        if(root == null) return null;
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        nodeQueue.offer(root);
        while(!nodeQueue.isEmpty()){
            TreeNode t1 = nodeQueue.poll();
            TreeNode left = t1.left;
            t1.left = t1.right;
            t1.right = left;
            if(t1.left!=null)
                nodeQueue.offer(t1.left);
            if(t1.right!=null)
                nodeQueue.offer(t1.right);
        }
        return root;
    }


你可能感兴趣的:(LeetCode,Queue)