【问题标题】:Counting the inner nodes (parent nodes) in a binary tree recursively递归计算二叉树中的内部节点(父节点)
【发布时间】:2014-08-12 15:08:14
【问题描述】:
我需要创建一个递归方法,将二叉搜索树的根节点作为参数。然后这个递归方法会返回整个二叉搜索树内部节点总数的int值。
这是我目前所拥有的:
int countNrOfInnerNodes (Node node) {
if(node == null) {
return 0;
}
if (node.left != null && node.right != null){
return 1;
}
return countNrOfInnerNodes(node.left)+countNrOfInnerNodes(node.right)
}
}
有没有更好的方法?我也坚持找到一个迭代解决方案。
【问题讨论】:
标签:
java
recursion
binary-tree
parent-node
【解决方案1】:
这是固定的递归方法:
int countNrOfInnerNodes (Node node) {
if(node == null) {
return 0;
}
if (node.left == null && node.right == null) {
// not an inner node !
return 0;
} else {
// the number of inner nodes in the left sub-tree + the number of inner
// nodes in the right sub-tree, plus 1 for this inner node
return countNrOfInnerNodes(node.left) + countNrOfInnerNodes(node.right) + 1;
}
}
这里是迭代方法:
int countNrOfInnerNodes(Node node) {
if (node == null)
return 0;
Stack<Node> nodesToCheck = new Stack<Node>();
nodesToCheck.push(node);
int count = 0;
while (!nodesToCheck.isEmpty()) {
Node checkedNode = nodesToCheck.pop();
boolean isInnerNode = false;
if (node.left != null) {
isInnerNode = true;
nodesToCheck.push(node.left);
}
if (node.right != null) {
isInnerNode = true;
nodesToCheck.push(node.right);
}
if (isInnerNode)
count++;
}
return count;
}