【leetcode】【Easy】【226. Invert Binary Tree】【tree】

problem link


code:

code1:递归在leetcode上要比BFS快一点

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

code2:BFS遍历整个树,比递归慢

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null)
            return null;
            
        Queue queue=new LinkedList();
        queue.offer(root);
        
        while(!queue.isEmpty()){
            TreeNode cur=queue.poll();
            
            //要考虑左右子树是否存在
            if(cur.left==null && cur.right!=null){//只存在右子树
                cur.left=cur.right;
                cur.right=null;
                queue.offer(cur.left);
            }else if(cur.right==null && cur.left!=null){//只存在左子树
                cur.right=cur.left;
                cur.left=null;
                queue.offer(cur.right);
            }else if(cur.left!=null && cur.right!=null){//左右子树都存在
                TreeNode temp=cur.left;
                cur.left=cur.right;
                cur.right=temp;
            
                queue.offer(cur.left);
                queue.offer(cur.right);
            }//左右子树都不存在不用操作
            
        }
        
        return root;
    }
}

while循环中的判断可以简化。

但是不懂为什么下面三行不会报NullPointerException??

TreeNode temp=cur.left;
cur.left=cur.right;
cur.right=temp;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null)
            return null;
            
        Queue queue=new LinkedList();
        queue.offer(root);
        
        while(!queue.isEmpty()){
            TreeNode cur=queue.poll();
            
            TreeNode temp=cur.left;
            cur.left=cur.right;
            cur.right=temp;
            
            if(cur.left!=null){
                queue.offer(cur.left);
            }
            
            if(cur.right!=null){
                queue.offer(cur.right);
            }
        }
        
        return root;
    }
}


你可能感兴趣的:(LeetCode_Easy)