-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedListinBinaryTree.py
More file actions
28 lines (25 loc) · 995 Bytes
/
linkedListinBinaryTree.py
File metadata and controls
28 lines (25 loc) · 995 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/linked-list-in-binary-tree/
# Author: Miao Zhang
# Date: 2021-04-27
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubPath(self, head: ListNode, root: TreeNode) -> bool:
if not root: return False
return self.isPath(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right)
def isPath(self, head: ListNode, root: TreeNode) -> bool:
if not head: return True
if not root: return False
if head.val != root.val: return False
return self.isPath(head.next, root.left) or self.isPath(head.next, root.right)