« Check if a tree contains x

Contains x

Given a generic tree and an integer x, check if x is present in the given tree or not. Return true if x is present, return false otherwise.

Input format :

The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node, data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.
The following line contains an integer, that denotes the value of x.

Output format :

The first and only line of output contains true, if x is present and false, otherwise.

Constraints:

Time Limit: 1 sec

Sample Input 1 :

10 3 20 30 40 2 40 50 0 0 0 0

40

Sample Output 1 :

true

Sample Input 2 :

10 3 20 30 40 2 40 50 0 0 0 0

4

Sample Output 2:

false

1#include <iostream>
2#include <queue>
3#include <vector>
4using namespace std;
5
6template <typename T>
7class TreeNode {
8 public:
9 T data;
10 vector<TreeNode<T>*> children;
11
12 TreeNode(T data) { this->data = data; }
13
14 ~TreeNode() {
15 for (int i = 0; i < children.size(); i++) {
16 delete children[i];
17 }
18 }
19};
20
21bool isPresent(TreeNode<int>* root, int x) {
22 // Write your code here
23 if(root == NULL){
24 return false;
25 }
26 if(root->data == x){
27 return true;
28 }
29 for(int i=0; i< root->children.size(); i++){
30 bool ans = isPresent(root->children[i], x);
31 if(ans){
32 return ans;
33 }
34 }
35 return false;
36}
37
38TreeNode<int>* takeInputLevelWise() {
39 int rootData;
40 cin >> rootData;
41 TreeNode<int>* root = new TreeNode<int>(rootData);
42
43 queue<TreeNode<int>*> pendingNodes;
44
45 pendingNodes.push(root);
46 while (pendingNodes.size() != 0) {
47 TreeNode<int>* front = pendingNodes.front();
48 pendingNodes.pop();
49 int numChild;
50 cin >> numChild;
51 for (int i = 0; i < numChild; i++) {
52 int childData;
53 cin >> childData;
54 TreeNode<int>* child = new TreeNode<int>(childData);
55 front->children.push_back(child);
56 pendingNodes.push(child);
57 }
58 }
59
60 return root;
61}
62
63int main() {
64 TreeNode<int>* root = takeInputLevelWise();
65 int x;
66 cin >> x;
67 cout << (isPresent(root, x) ? "true" : "false");
68}