-
Notifications
You must be signed in to change notification settings - Fork 3
/
Count-Full-Half-Leaf-Nodes
84 lines (72 loc) · 1.99 KB
/
Count-Full-Half-Leaf-Nodes
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
package com.tree.traversal.recursive;
import java.util.LinkedList;
import java.util.Queue;
public class CountFullHalfLeafNodes {
static int fullNodes = 0;
static int halfNodes = 0;
static int leafNodes = 0;
public static void main(String[] args) {
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(3);
TreeNode root = new TreeNode(1, left, right);
left.left = new TreeNode(4);
right.left = new TreeNode(5, new TreeNode(7), null);
right.right = new TreeNode(7, null, new TreeNode(8));
countNodesRecursive(root);
System.out.println("Recursive \nFull Nodes -> "+fullNodes);
System.out.println("Half Nodes -> "+halfNodes);
System.out.println("Leaf Nodes -> "+leafNodes);
fullNodes = 0; halfNodes = 0; leafNodes = 0;
countNodesIterative(root);
System.out.println("\nIterative \nFull Nodes -> "+fullNodes);
System.out.println("Half Nodes -> "+halfNodes);
System.out.println("Leaf Nodes -> "+leafNodes);
}
private static void countNodesIterative(TreeNode root) {
if(root == null)
return;
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()) {
TreeNode current = q.remove();
if(current.left != null && current.right != null) {
fullNodes++;
q.add(current.left);
q.add(current.right);
}
else if(current.left != null || current.right != null) {
halfNodes++;
q.add(current.left != null ? current.left : current.right);
}
else
leafNodes++;
}
}
private static void countNodesRecursive(TreeNode node) {
if(node == null)
return;
if(node.left != null && node.right != null)
fullNodes++;
else if(node.left != null || node.right != null)
halfNodes++;
else
leafNodes++;
countNodesRecursive(node.left);
countNodesRecursive(node.right);
}
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}