-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProblem_01.java
More file actions
85 lines (75 loc) · 1.95 KB
/
Copy pathProblem_01.java
File metadata and controls
85 lines (75 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
* Check if generic tree contain element x
*
* Send Feedback
* 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 :
* Line 1 : Integer x
* Line 2 : Elements in level order form separated by space (as per done in class).
*
* Order is -
* Root_data , n (No_Of_Child_Of_Root) , n children , and so on for every element.
*
* Output format : true or false
* Sample Input 1 :
* 40
* 10 3 20 30 40 2 40 50 0 0 0 0
*
* Sample Output 1 :
* true
*
* Sample Input 2 :
* 4
* 10 3 20 30 40 2 40 50 0 0 0 0
*
* Sample Output 2:
* false
*/
package trees;
import java.util.*;
public class Problem_01 {
// TreeNode class
class TreeNode<T> {
T data;
ArrayList<TreeNode<T>> children;
TreeNode(T data){
this.data = data;
children = new ArrayList<TreeNode<T>>();
}
}
public static boolean checkIfContainsX(TreeNode<Integer> root, int x){
// Write your code here
if(root==null)
return false;
// Write your code here
Queue<TreeNode<Integer>> queue = new LinkedList<>();
//added 1st level here
queue.add(root);
queue.add(null);
@SuppressWarnings("unused")
int ans=0;
// if(x<root.data)
// ans++;
while(!queue.isEmpty())
{
TreeNode<Integer> frontNode = queue.remove();
if(frontNode == null)
{
if(queue.isEmpty())
break;
queue.add(null);
}
else{
if(frontNode.data==x)
return true;
System.out.print(frontNode.data+" ");
for(int i=0;i<frontNode.children.size();i++)
queue.add(frontNode.children.get(i));
}
}
return false;
}
}