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
Treee data structure with 7 nodes and 4 leaf nodes
计算叶节点数

在上面的示例中,我们在 Java 中实现了树数据结构。这里,我们使用 递归 来计算树中的叶节点数。


另请阅读:

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战