计算树中的左子节点数
我应该实现一个递归方法来计算左子树节点的数量。到目前为止,我的代码是:
private int countLeftNodes(IntTreeNode node){
int c = 0;
if (node != null){
c = 1 + countLeftNodes(node.left);
countLeftNodes(node.right);
}
return c;
}
它返回的数字比应有的小得多。我有一种感觉,我的遍历已经关闭,因为它似乎只计算最左边的子节点,然后终止。当我在大小为 16 的 IntTree 上调用此方法时,我应该得到 8 个左子节点、7 个右子节点和 1 个根,但我得到的是 4 个左子节点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你永远不会计算右树中的左节点。
You never count the left nodes in the right tree.
要计算左子节点,您可以执行以下操作:
To count left-child nodes you can do:
最容易检查的地方是父级。
easiest place to check that is in the parent.
使用递归时我最喜欢的风格是使用某种包装函数,其中主方法调用另一个执行繁重工作的函数:
注意主函数如何调用另一个函数。我发现这种风格更干净、更容易理解。另外,第二个函数有一个计数变量供您使用。
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:
Notice how the main function calls another. I find this style to be cleaner and easier to understand. Also, the second function has a count variable for you to use.