本文主要是介绍Leetcode 1367. Linked List in Binary Tree [Python],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
设置dfs的helper函数,定义为如果当前节点值相同,linklist的下一个节点和tree的left节点或者right节点继续相同,则当linklist的节点比较完成,说明满足条件。反之,走完tree某个路径上的节点依然找不到,则说明这条路径上没有满足条件的。外层的函数比较linkedlist的头节点和tree的根节点或者根节点的左子或者右子节点。
class Solution:def isSubPath(self, head: ListNode, root: TreeNode) -> bool:if not root:return Falseif not head:return Truedef dfs(head, root):if not head:return Trueif not root:return Falseif head.val == root.val and (dfs(head.next, root.left) or dfs(head.next, root.right)):return Truereturn Falseif dfs(head, root) or self.isSubPath(head, root.left) or self.isSubPath(head, root.right):return Truereturn False
这篇关于Leetcode 1367. Linked List in Binary Tree [Python]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!