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

本文介绍了两种实现二叉树节点翻转的方法:递归方式和广度优先搜索(BFS)。递归方法通过交换每个节点的左右子树来翻转整棵树,在LeetCode上的性能优于BFS。BFS则通过队列遍历并交换每个节点的子树。

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<TreeNode> queue=new LinkedList<TreeNode>();
        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<TreeNode> queue=new LinkedList<TreeNode>();
        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;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值