二叉树中的列表

二叉树中的列表

给你一棵以 root 为根的二叉树和一个 head 为第一个节点的链表。
如果在二叉树中,存在一条一直向下的路径,且每个点的数值恰好一一对应以
head 为首的链表中每个节点的值,那么请你返回 True ,否则返回 False 。
一直向下的路径的意思是:从树中某个节点开始,一直连续向下的路径。

题解:老规矩,依次挨个节点遍历,
返回值:
1.当root为空时返回false
2.当值不相等时返回false
3.当head为null时返回true

递归条件:当前节点不匹配,那好,我们遍历左右子节点

public class isSubPath {

    public  boolean isSubPath(ListNode head, TreeNode root){
        if (head==null){
            return true;
        }
        if (root==null){
            return false;
        }
        return isSub(head,root)||isSubPath(head,root.left)||isSubPath(head,root.right);
    }
    public boolean isSub(ListNode head,TreeNode root){
        if (head==null){
            return true;
        }
        if (root==null){
            return false;
        }
        if (head.val!=root.val){
            return false;
        }
        return isSub(head.next,root.left)||isSub(head.next,root.right);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30926503/article/details/107541551