题解 | #树的子结构#

树的子结构

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

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.*;
public class Solution {
    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);
    }
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if(root1==null || root2==null) return false;
//         root2和root1比 root2和root1的左子树比 root2和root1的右子树比 
        return isSame(root1,root2) || HasSubtree(root1.left,root2) || HasSubtree(root1.right,root2);
    }
}

之前思路:中序+先序 比较其遍历一次之后的string ❌ 12345 123这种就不可以 只能后序+中序 并且这种要遍历多次

层序遍历 其实和递归一样,都是遍历找root1的节点 相同,假设其为相同的根节点,进行比较, 不同就再找其子节点,如果有一样的再假设为根节点

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.LinkedList;
import java.util.Queue;

public class Solution {
    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);
    }
    public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if(root1==null || root2==null) return false;
        Queue<TreeNode>q = new LinkedList<>();
        q.offer(root1);
        while(!q.isEmpty()){
            TreeNode cur = q.poll();
            if(isSame(cur,root2)) return true;
            else{
                if(cur.left!=null) q.offer(cur.left);
                if(cur.right!=null) q.offer(cur.right);
            }
            
        }
        return false;
    }
}
全部评论

相关推荐

09-23 15:37
门头沟学院 Java
面了100年面试不知...:ai面:请你说一下在无的论文/项目中,你具体做了什么
我的秋招日记
点赞 评论 收藏
分享
08-06 08:33
四川大学 Java
OPPO官方内推:卧槽!!!啥破公司啊!!!
投递OPPO等公司10个岗位
点赞 评论 收藏
分享
三轮业务+一轮HR&nbsp;俺有点没招了。。。
此刻我身在乌云中:hr打电话问我能不能提前实习,我说不可以,然后他说那可能要横向排序等结果。结果五分钟立马挂了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务