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 宁夏
滴滴
校招火热招聘中
官网直投

相关推荐

14 2 评论
分享
牛客网
牛客企业服务