English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

使用Java程序计算树中叶节点的数量

    Java example complete set

在此示例中,我们将学习如何使用Java计算树中叶节点的数量。

示例:使用Java程序计算树中叶节点的数量

class Node {
  int item;
  Node left, right;
  public Node(int key) {
  item = key;
  left = right = null;
  }
}
class Main {
  //树根
  Node root;
  Main() {
  root = null;
  }
  //计算叶节点的方法
  public static int countLeaf(Node node) {
    if(node == null) {
      return 0;
    }
    //如果节点的左、右为空
    //它是叶节点
    if (node.left == null && node.right == null) {
      return 1;
    }
    else {
      return countLeaf(node.left) + countLeaf(node.right);
    }
  }
  public static void main(String[] args) {
    //创建一个Tree对象
    Main tree = new Main();
    //创建树的节点
    tree.root = new Node(5);
    tree.root.left = new Node(3);
    tree.root.right = new Node(8);
    //Create the child node of the left child
    tree.root.left.left = new Node(2);
    tree.root.left.right = new Node(4);
    //Create the child node of the right child
    tree.root.right.left = new Node(7);
    tree.root.right.right = new Node(9);
    //Call the method to calculate the number of leaf nodes
    int leafNodes = countLeaf(tree.root);
    System.out.println("Total number of leaf nodes = "); + leafNodes);
  }
}

Output result

Total number of leaf nodes = 4
Calculate the number of leaf nodes

In the above example, we have implemented the tree data structure in Java. Here, we use recursion to calculate the number of leaf nodes in the tree.

Recommended:

Java example complete set