algorithm - 二叉树中的叶子数

标签 algorithm binary-search-tree binary-search

我是二叉树的初学者,一直在努力学习算法书。我了解了 BST 的各种遍历方法(前序、后序等)。

有人可以解释一下如何遍历 BST 来计算叶子节点(没有子节点)的数量吗?

非常感谢!

最佳答案

使用递归方法:

  • 对于叶子返回1。
  • 对于非叶节点,返回应用于其子节点的该方法的总和。

PHP 示例:

class BST {
  public $left;  // The substree containing the smaller entries
  public $right; // The substree containing the larger entries
  public $data;  // The value that is stored in the node
}

function countLeafs(BST $b) {
  // Test whether children exist ...
  if ($b->left || $b->right) {
    // ... yes, the left or the right child exists. It's not a leaf.
    // Return the sum of calling countLeafs() on all children.
    return ($b->left  ? countLeafs($b->left)  : 0)
         + ($b->right ? countLeafs($b->right) : 0);
  } else {
    // ... no, it's a leaf
    return 1;
  }
}

关于algorithm - 二叉树中的叶子数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568800/

相关文章:

algorithm - 寻找具有最大平均度数的子图。复杂?

algorithm - 二进制搜索在这种情况下不起作用?

c - C 中的 BinarySearchTree - deleteWord - 保留对从树中删除的元素的引用

Java:查找 BST 中未找到的节点的深度

c - 使用二进制搜索优化大型 if-else 分支

java - 从 10000 个 ascii 字符串返回一个字符串子集

MySQL如何在一列内进行排列并运行计算?

c++ - 二进制搜索查找排序数组中比给定值最小和最大的元素?

c++ - 在二叉搜索树中插入值

c - 在字符串中查找动词