-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathBinaryTree2.java
More file actions
41 lines (34 loc) · 933 Bytes
/
BinaryTree2.java
File metadata and controls
41 lines (34 loc) · 933 Bytes
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
class TreeNode {
int data;
TreeNode left, right;
public TreeNode(int data) {
this.data = data;
left = right = null;
}
}
class BinaryTree {
TreeNode root;
BinaryTree() {
root = null;
}
int countNodes(TreeNode node) {
if (node == null)
return 0;
return 1 + countNodes(node.left) + countNodes(node.right);
}
int getNumberOfNodes() {
return countNodes(root);
}
}
public class Main {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.left.left = new TreeNode(4);
tree.root.left.right = new TreeNode(5);
int nodeCount = tree.getNumberOfNodes();
System.out.println("Number of nodes in the binary tree: " + nodeCount);
}
}