File tree 1 file changed +66
-0
lines changed
Course 2 - Data Structures in JAVA/Lecture 11 - Binary Trees I
1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ For a given Binary Tree of type integer and a number X, find whether a node exists in the tree with data X or not.
3
+
4
+ Input Format:
5
+ The first and the only line of input will contain the node data, all separated by a single space.
6
+ Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of the node data.
7
+
8
+ Output Format:
9
+ The only line of output prints 'true' or 'false'.
10
+ Note: You are not required to print anything explicitly. It has already been taken care of.
11
+
12
+ Constraints:
13
+ 1 <= N <= 10^5
14
+ Where N is the total number of nodes in the binary tree.
15
+ Time Limit: 1 sec
16
+
17
+ Sample Input 1:
18
+ 8 3 10 1 6 -1 14 -1 -1 4 7 13 -1 -1 -1 -1 -1 -1 -1
19
+ 7
20
+ Sample Output 1:
21
+ true
22
+
23
+ Sample Input 2:
24
+ 2 3 4 -1 -1 -1 -1
25
+ 10
26
+ Sample Output 2:
27
+ false
28
+ */
29
+ /*
30
+
31
+ Following is the structure used to represent the Binary Tree Node
32
+
33
+ class BinaryTreeNode<T> {
34
+ T data;
35
+ BinaryTreeNode<T> left;
36
+ BinaryTreeNode<T> right;
37
+
38
+ public BinaryTreeNode(T data) {
39
+ this.data = data;
40
+ this.left = null;
41
+ this.right = null;
42
+ }
43
+ }
44
+
45
+ */
46
+
47
+ public class Solution {
48
+
49
+ public static boolean isNodePresent(BinaryTreeNode<Integer> root, int x) {
50
+ //Your code goes here
51
+ if (root==null)
52
+ {
53
+ return false;
54
+ }
55
+
56
+ if (root.data==x)
57
+ {
58
+ return true;
59
+ }
60
+ else
61
+ {
62
+ return (isNodePresent(root.left,x)||isNodePresent(root.right,x));
63
+ }
64
+ }
65
+
66
+ }
You can’t perform that action at this time.
0 commit comments