Java教程

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

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

在这个例子中,我们将学习使用 Java 计算树中叶节点的数量。
要理解此示例,您应该了解以下Java 编程主题:
Java 类和对象 Java 方法

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

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);
  }
}
输出
Total Leaf Nodes = 4
在上面的例子中,我们已经用Java实现了树数据结构。在这里,我们使用递归来计算树中叶节点的数量。

推荐阅读:

树数据结构 Java中的二叉树实现
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4