VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-root-leaf-path-given-sequence/

⇱ Check if there is a root to leaf path with given sequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if there is a root to leaf path with given sequence

Last Updated : 11 Oct, 2024

Given a binary tree and an array, the task is to find if the given array sequence is present as a root-to-leaf path in given tree.

Examples:

Input: arr = {5, 2, 4, 8}

👁 Check-if-there-is-a-root-to-leaf-path-with-given-sequence


Output: True
Explanation: The given array sequence {5, 2, 4, 8} is present as a root-to-leaf path in given tree.

Input: arr = {5, 3, 4, 9}

👁 Check-if-there-is-a-root-to-leaf-path-with-given-sequence

Output: False
Explanation: The given array sequence {5, 3, 4, 9} is not present as a root-to-leaf path in given tree.

simple solution for this problem is to find all root-to-leaf paths in given tree and for each root-to-leaf path check whether path and given sequence in array both are identical or not.

Approach:

The idea is to traverse the tree once and while traversing the tree we have to check if path from root to current node is identical to the given sequence of root to leaf path. 

Algorithm:

  • Start traversing tree in preorder fashion.
  • Whenever we moves down in tree then we also move by one index in given sequence of root to leaf path .
  • If current node is equal to the arr[index] this means that till this level of tree path is identical.
  • Now remaining path will either be in left subtree or in right subtree.
  • If any node gets mismatched with arr[index] this means that current path is not identical to the given sequence of root to leaf path, so we return back and move in right subtree.
  • Now when we are at leaf node and it is equal to arr[index] and there is no further element in given sequence of root to leaf path, this means that path exist in given tree.

Below is the implementation of the above approach:


Output
True

Time Complexity: O(n), where n is the number of nodes in the tree. 
Auxiliary Space: O(h), due to the recursive call stack, where h is the height of the tree.

Comment
Article Tags:
Article Tags: