Write a Java Program to Count number of leaf nodes in a tree

Write a Java Program to Count number of leaf nodes in a tree

 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
class Node {
  int item;
  Node left, right;

  public Node(int key) {
  item = key;
  left = right = null;
  }
}

class Main {
  // root of Tree
  Node root;

  Main() {
  root = null;
  }

  // method to count leaf nodes
  public static int countLeaf(Node node) {
    if(node == null) {
      return 0;
    }

    // if left and right of the node is null
    // it is leaf node
    if (node.left == null && node.right == null) {
      return 1;
    }
    else {
      return countLeaf(node.left) + countLeaf(node.right);
    }
  }

  public static void main(String[] args) {

    // create an object of Tree
    Main tree = new Main();

    // create nodes of tree
    tree.root = new Node(5);
    tree.root.left = new Node(3);
    tree.root.right = new Node(8);

    // create child nodes of left child
    tree.root.left.left = new Node(2);
    tree.root.left.right = new Node(4);

    // create child nodes of right child
    tree.root.right.left = new Node(7);
    tree.root.right.right = new Node(9);

    // call method to count leaf nodes
    int leafNodes = countLeaf(tree.root);
    System.out.println("Total Leaf Nodes = " + leafNodes);
  }
}

Final output

Leave a Comment