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}
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}
Output: False
Explanation: The given array sequence {5, 3, 4, 9} is not 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 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:
C++
// C++ code to check if the given array
// sequence exists as a root-to-leaf path
#include <iostream>
#include <vector>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Function to check if the path exists
bool checkPath(Node* root, vector<int>& arr,
int index) {
// If root is NULL or index exceeds
//array size, return false
if (!root || index >= arr.size()) {
return false;
}
// If current node does not match the
// array element, return false
if (root->data != arr[index]) {
return false;
}
// If we reach the leaf node and the
// sequence matches fully
if (!root->left && !root->right
&& index == arr.size() - 1) {
return true;
}
// Recurse for left and right subtrees by moving
// to next index in arr
return checkPath(root->left, arr, index + 1) ||
checkPath(root->right, arr, index + 1);
}
int main() {
// Representation of the given tree
// 5
// / \
// 2 3
// / \
// 1 4
// / \
// 6 8
Node* root = new Node(5);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(1);
root->left->right = new Node(4);
root->left->right->left = new Node(6);
root->left->right->right = new Node(8);
vector<int> arr = {5, 2, 4, 8};
if (checkPath(root, arr, 0)) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}
Java
// Java code to check if the given array sequence
// exists as a root-to-leaf path in a binary tree
import java.util.ArrayList;
import java.util.Arrays;
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to check if the path exists
static boolean checkPath(Node root,
ArrayList<Integer> arr, int index) {
// If root is null or index exceeds
// array size, return false
if (root == null || index >= arr.size()) {
return false;
}
// If current node does not match the
// array element, return false
if (root.data != arr.get(index)) {
return false;
}
// If we reach the leaf node and the
// sequence matches fully
if (root.left == null && root.right == null
&& index == arr.size() - 1) {
return true;
}
// Recurse for left and right subtrees
// by moving to next index in arr
return checkPath(root.left, arr, index + 1) ||
checkPath(root.right, arr, index + 1);
}
// Function to check if the sequence exists
static void isPathExist(Node root,
ArrayList<Integer> arr) {
}
public static void main(String[] args) {
// Representation of the given tree
// 5
// / \
// 2 3
// / \
// 1 4
// / \
// 6 8
Node root = new Node(5);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.left.right.left = new Node(6);
root.left.right.right = new Node(8);
ArrayList<Integer> arr
= new ArrayList<>(Arrays.asList(5, 2, 4, 8));
if (checkPath(root, arr, 0)) {
System.out.println("True");
} else {
System.out.println("False");
}
}
}
Python
# Python code to check if the given array sequence
# exists as a root-to-leaf path in a binary tree
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to check if the path exists
def check_path(root, arr, index):
# If root is None or index exceeds
# array size, return False
if not root or index >= len(arr):
return False
# If current node does not match the
# array element, return False
if root.data != arr[index]:
return False
# If we reach the leaf node and the
# sequence matches fully
if not root.left and not root.right \
and index == len(arr) - 1:
return True
# Recurse for left and right subtrees
# by moving to next index in arr
return check_path(root.left, arr, index + 1) \
or check_path(root.right, arr, index + 1)
if __name__ == "__main__":
# Representation of the given tree
# 5
# / \
# 2 3
# / \
# 1 4
# / \
# 6 8
root = Node(5)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(1)
root.left.right = Node(4)
root.left.right.left = Node(6)
root.left.right.right = Node(8)
arr = [5, 2, 4, 8]
if check_path(root, arr, 0):
print("True")
else:
print("False")
C#
// C# code to check if the given array sequence
// exists as a root-to-leaf path in a binary tree
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to check if the path exists
static bool CheckPath(Node root, List<int> arr,
int index) {
// If root is null or index exceeds
// array size, return false
if (root == null || index >= arr.Count) {
return false;
}
// If current node does not match
// the array element, return false
if (root.data != arr[index]) {
return false;
}
// If we reach the leaf node and
// the sequence matches fully
if (root.left == null && root.right == null
&& index == arr.Count - 1) {
return true;
}
// Recurse for left and right subtrees by
// moving to next index in arr
return CheckPath(root.left, arr, index + 1) ||
CheckPath(root.right, arr, index + 1);
}
static void Main(string[] args) {
// Representation of the given tree
// 5
// / \
// 2 3
// / \
// 1 4
// / \
// 6 8
Node root = new Node(5);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.left.right.left = new Node(6);
root.left.right.right = new Node(8);
List<int> arr = new List<int> { 5, 2, 4, 8 };
if (CheckPath(root, arr, 0)) {
Console.WriteLine("True");
} else {
Console.WriteLine("False");
}
}
}
JavaScript
// JavaScript code to check if the given array sequence
// exists as a root-to-leaf path in a binary tree
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function to check if the path exists
function checkPath(root, arr, index) {
// If root is null or index exceeds
// array size, return false
if (!root || index >= arr.length) {
return false;
}
// If current node does not match the
// array element, return false
if (root.data !== arr[index]) {
return false;
}
// If we reach the leaf node and
// the sequence matches fully
if (!root.left && !root.right &&
index === arr.length - 1) {
return true;
}
// Recurse for left and right subtrees
// by moving to next index in arr
return checkPath(root.left, arr, index + 1) ||
checkPath(root.right, arr, index + 1);
}
// Representation of the given tree
// 5
// / \
// 2 3
// / \
// 1 4
// / \
// 6 8
const root = new Node(5);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(1);
root.left.right = new Node(4);
root.left.right.left = new Node(6);
root.left.right.right = new Node(8);
const arr = [5, 2, 4, 8];
if (checkPath(root, arr, 0)) {
console.log("True");
} else {
console.log("False");
}
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.
Similar Reads
Binary Tree Data Structure A Binary Tree Data Structure is a hierarchical data structure in which each node has at most two children, referred to as the left child and the right child. It is commonly used in computer science for efficient storage and retrieval of data, with various operations such as insertion, deletion, and
3 min read
Introduction to Binary Tree Binary Tree is a non-linear and hierarchical data structure where each node has at most two children referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. Introduction to Binary TreeRepresentation of Bina
15+ min read
Properties of Binary Tree This post explores the fundamental properties of a binary tree, covering its structure, characteristics, and key relationships between nodes, edges, height, and levelsBinary tree representationNote: Height of root node is considered as 0. Properties of Binary Trees1. Maximum Nodes at Level 'l'A bina
4 min read
Applications, Advantages and Disadvantages of Binary Tree A binary tree is a tree that has at most two children for any of its nodes. There are several types of binary trees. To learn more about them please refer to the article on "Types of binary tree" Applications:General ApplicationsDOM in HTML: Binary trees help manage the hierarchical structure of web
2 min read
Binary Tree (Array implementation) Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Maximum Depth of Binary Tree Given a binary tree, the task is to find the maximum depth of the tree. The maximum depth or height of the tree is the number of edges in the tree from the root to the deepest node.Examples:Input: Output: 2Explanation: The longest path from the root (node 12) goes through node 8 to node 5, which has
11 min read
Insertion in a Binary Tree in level order Given a binary tree and a key, the task is to insert the key into the binary tree at the first position available in level order manner.Examples:Input: key = 12 Output: Explanation: Node with value 12 is inserted into the binary tree at the first position available in level order manner.Approach:The
8 min read
Deletion in a Binary Tree Given a binary tree, the task is to delete a given node from it by making sure that the tree shrinks from the bottom (i.e. the deleted node is replaced by the bottom-most and rightmost node). This is different from BST deletion. Here we do not have any order among elements, so we replace them with t
12 min read
Enumeration of Binary Trees A Binary Tree is labeled if every node is assigned a label and a Binary Tree is unlabelled if nodes are not assigned any label. Below two are considered same unlabelled trees o o / \ / \ o o o o Below two are considered different labelled trees A C / \ / \ B C A B How many different Unlabelled Binar
3 min read
Types of Binary Tree