-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLargestelementinbinarytree.java
More file actions
131 lines (57 loc) · 2.25 KB
/
Copy pathLargestelementinbinarytree.java
File metadata and controls
131 lines (57 loc) · 2.25 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
public class LargestNode {
//Represent the node of binary tree
public static class Node{
int data;
Node left;
Node right;
public Node(int data){
//Assign data to the new node, set left and right children to null
this.data = data;
this.left = null;
this.right = null;
}
}
//Represent the root of binary tree
public Node root;
public LargestNode(){
root = null;
}
//largestElement() will find out the largest node in the binary tree
public int largestElement(Node temp){
//Check whether tree is empty
if(root == null) {
System.out.println("Tree is empty");
return 0;
}
else{
int leftMax, rightMax;
//Max will store temp's data
int max = temp.data;
//It will find largest element in left subtree
if(temp.left != null){
leftMax = largestElement(temp.left);
//Compare max with leftMax and store greater value into max
max = Math.max(max, leftMax);
}
//It will find largest element in right subtree
if(temp.right != null){
rightMax = largestElement(temp.right);
//Compare max with rightMax and store greater value into max
max = Math.max(max, rightMax);
}
return max;
}
}
public static void main(String[] args) {
LargestNode bt = new LargestNode();
//Add nodes to the binary tree
bt.root = new Node(15);
bt.root.left = new Node(20);
bt.root.right = new Node(35);
bt.root.left.left = new Node(74);
bt.root.right.left = new Node(55);
bt.root.right.right = new Node(6);
//Display largest node in the binary tree
System.out.println("Largest element in the binary tree: " + bt.largestElement(bt.root));
}
}