计算每个节点的子节点数

时间:2016-12-18 10:17:23

标签: data-structures tree binary-tree

给出一棵树:

      F
    /   \
   C     E
  / \   /
 A   B D

我想计算每个节点的子节点数。什么是优化算法?

1 个答案:

答案 0 :(得分:0)

如果子计数应该包括孙子,请进行后序遍历,递归计算O(n)中的分支大小:

int countChildren(Node node) {
  int leftCount = node.left == null ? 0 : (countChildren(root.left) + 1);
  int rightCount = node.right == null ? 0 : (countChildren(root.right) + 1);

  int totalChildren = leftCount + rightCount;

  System.out.println(node.name + ":" + totalChildren);

  return totalChildren;
}