[英]Counting left-child nodes in a Tree
I am supposed to implement a recursive method that counts the amount of left-child tree nodes. 我应该实现一个递归方法来计算左子树节点的数量。 My code so far is:
到目前为止我的代码是:
private int countLeftNodes(IntTreeNode node){
int c = 0;
if (node != null){
c = 1 + countLeftNodes(node.left);
countLeftNodes(node.right);
}
return c;
}
It returns a number much smaller than what it should be. 它返回的数字远小于应有的数字。 I have a feeling that my traversal is off because it seems to only count the very left child nodes, and then terminates.
我有一种感觉,我的遍历已关闭,因为它似乎只计算左边的子节点,然后终止。 When I call this method on an IntTree of size 16 I should get 8 left-child nodes, 7 right-child nodes, and one root, but instead I get 4 left-child nodes.
当我在大小为16的IntTree上调用此方法时,我应该得到8个左子节点,7个右子节点和一个根,但我得到4个左子节点。
You never count the left nodes in the right tree. 您永远不会计算右侧树中的左侧节点。
private int countLeftNodes(IntTreeNode node)
{
int c = 0;
if (node.left != null)
{
c += 1 + countLeftNodes(node.left);
}
if(node.right != null)
{
c += countLeftNodes(node.right);
}
return c;
}
To count left-child nodes you can do: 要计算左子节点,您可以执行以下操作:
private int countLeftNodes(IntTreeNode node) {
// no tree no left-child nodes
if(node == null) {
return 0;
}
// left-child count of current node.
int c = 0;
// does the current node have a left-child ?
if (node.left != null){
c = 1;
}
// return left-child count of current node +
// left-child count of left and right subtrees
return c + countLeftNodes(node.left) + countLeftNodes(node.right);
}
private int countLeftNodes(IntTreeNode node){
int c = 0;
if (node != null){
if(node.left!=null) {
c = 1 + countLeftNodes(node.left);
}
if(node.right!=null){
c +=countLeftNodes(node.right);
}
}
return c;
}
easiest place to check that is in the parent. 最容易检查的地方是父母。
private int countLeftNodes(IntTreeNode node){
int c = 0;
if(node.left != null)
{
c++;
c+= countLeftNodes(node.left)
}
if(node.right != null)
{
c+= countLeftNodes(node.right);
}
return c;
}
My favorite style when using recursion is to use a wrapper function of some sort where the main method calls another that does the grunt work: 使用递归时我最喜欢的样式是使用某种类型的包装器函数,其中main方法调用另一种执行grunt工作的函数:
private int countLeftNodes(IntTreeNode node){
int totalCount = reallyCountLeftNodes(IntTreeNode node, 0);
return totalCount;
}
private int reallyCountLeftNodes(IntTreeNode n, Int sum){
if (n.left == NULL && n.right == NULL){ //check if we've hit rock bottom
return sum;
} else if (n.left == NULL) { //if the node's left is nil, go right
reallyCountLeftNodes(n.right, sum++);
} else {
reallyCountLeftNodes(n.left, sum++); // Going as far left as possible!
}
}
Notice how the main function calls another. 注意main函数如何调用另一个函数。 I find this style to be cleaner and easier to understand.
我发现这种风格更清晰,更容易理解。 Also, the second function has a count variable for you to use.
此外,第二个函数有一个count变量供您使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.