Leetcode Invert Binary Tree

Invert a binary tree.

     4
   /   
  2     7
 /    / 
1   3 6   9

to

     4
   /   
  7     2
 /    / 
9   6 3   1


解题思路:

方法一: recursion 交换当前左右节点,并直接调用递归即可
方法二: 跟二叉树的层序遍历一样,需要用queue来辅助,先把根节点排入队列中,然后从队中取出来,交换其左右节点,如果存在则分别将左右节点在排入队列中,以此类推直到队列中木有节点了停止循环,返回root即可。


 Java code:

方法一 recursion:

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

方法二:

public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return root;
        }
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int curNum = 1; //num of node left in current level
        int nextNum = 0; // num of nodes in next level
        while(!queue.isEmpty()) {
             TreeNode n = queue.poll(); 
             curNum--;
             if(n.left!= null || n.right != null){
                TreeNode temp = n.left;
                n.left = n.right;
                n.right = temp;
            }
            if(n.left != null) {
                queue.add(n.left);
                nextNum++;
            }
            if(n.right != null) {
                queue.add(n.right);
                nextNum++;
            }
            if(curNum == 0) {
                curNum = nextNum;
                nextNum = 0;
            }
        }
        return root;
    }

Reference:

1. http://www.cnblogs.com/grandyang/p/4572877.html

原文地址:https://www.cnblogs.com/anne-vista/p/4806030.html