Check if there is a root to leaf path with given sequence - GeeksforGeeks
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.
Read full article from Check if there is a root to leaf path with given sequence - GeeksforGeeks
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.
A simple solution for this problem is to find all root to leaf paths in given tree and for each root to leaf path check that path and given sequence in array both are identical or not.
An efficient solution for this problem is to traverse the tree once and while traversing the tree we have to check that if path from root to current node is identical to the given sequence of root to leaf path. Here is the 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.
bool
existPath(
struct
Node *root,
int
arr[],
int
n,
int
index)
{
// If root is NULL, then there must not be any element
// in array.
if
(root == NULL)
return
(n == 0);
// If this node is a leaf and matches with last entry
// of array.
if
((root->left == NULL && root->right == NULL) &&
(root->data == arr[index]) && (index == n-1))
return
true
;
// If current node is equal to arr[index] this means
// that till this level path has been matched and
// remaining path can be either in left subtree or
// right subtree.
return
((index < n) && (root->data == arr[index]) &&
(existPath(root->left, arr, n, index+1) ||
existPath(root->right, arr, n, index+1) ));
}