-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCheckIfGenericTreeContainElementX.java
More file actions
68 lines (54 loc) · 1.49 KB
/
CheckIfGenericTreeContainElementX.java
File metadata and controls
68 lines (54 loc) · 1.49 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
// 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
// Explanation
// Since, 40 is present in the given tree, so the answer will be true.
// Sample Input 2 :
// 4
// 10 3 20 30 40 2 40 50 0 0 0 0
// Sample Output 2:
// false
// Explanation
// Since, 4 is not present in the given tree, so the answer is false.
public class Solution {
/*
* 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;
}
if (root.data == x) {
return true;
}
for (int i = 0; i < root.children.size(); i++) {
if (checkIfContainsX(root.children.get(i), x)) {
return true;
}
}
return false;
}
}