java两种方法实现(递归与非递归)

树的子结构

http://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88

首先:判断结构相同必须需要的函数
public boolean isSame(TreeNode root1,TreeNode root2){
        if(root2 == null) return true;           
        if(root1 == null) return false;        
        return root1.val == root2.val 
            && isSame(root1.left, root2.left)
            && isSame(root1.right, root2.right);
    }

第一种:递归判断  利用好短路特性 20ms
public boolean fun1(TreeNode root1, TreeNode root2) {
        if(root1 == null || root2 == null) return false;
        return isSame(root1, root2) || isSame(root1.left, root2) || isSame(root1.right,root2); 
    }

第二:非递归实现:广度优先遍历判断 14ms
public boolean fun2(TreeNode root1, TreeNode root2) {
        if(root1 == null || root2 == null){
            return false;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root1);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(isSame(cur, root2)) return true;
            else{
                if(cur.left != null) queue.offer(cur.left);
                if(cur.right != null) queue.offer(cur.right);
            }
        }
        return false;
    }
全部评论
采用递归那里应该是这样吧:return isSame(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right,root2);
7 回复 分享
发布于 2021-11-21 11:39
正解
点赞 回复 分享
发布于 2023-09-04 11:03 宁夏

相关推荐

不愿透露姓名的神秘牛友
02-03 10:14
求各位大佬帮忙改改简历提提建议
黑皮白袜臭脚体育生:简历条例统一按使用了什么技术实现了什么功能解决了什么问题或提升了什么性能指标来写 可以看我帖子简历话术写法
点赞 评论 收藏
分享
2024-12-11 11:40
海南大学 Java
点赞 评论 收藏
分享
2024-12-16 21:59
东北大学 Java
水杉1:我评估了仨月了
点赞 评论 收藏
分享
评论
14
2
分享

创作者周榜

更多
牛客网
牛客企业服务