bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 1367. Linked List in Binary Tree

1367. Linked List in Binary Tree

Leetcode Solutions

Recursive Depth-First Search

  1. Define a helper function dfs that takes a tree node and a list node as arguments.
  2. If the list node is null, return true (end of the linked list reached).
  3. If the tree node is null, return false (end of the path in the tree reached).
  4. If the values of the tree node and list node match, recursively call dfs with the next list node and both children of the tree node.
  5. Define the main function isSubPath that initiates the DFS search from the root of the tree.
  6. If the current tree node matches the head of the linked list, call dfs with the current tree node and head of the linked list.
  7. Regardless of the match, continue the search by calling isSubPath on the left and right children of the current tree node.
  8. Return true if any of the recursive calls return true, otherwise return false.
UML Thumbnail

Iterative Depth-First Search with Stack

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...