Java 寻找树上的叶子
我正试图找到一棵树上的树叶。我想做递归,但我不能接受零以外的输出。谢谢Java 寻找树上的叶子,java,binary-tree,Java,Binary Tree,我正试图找到一棵树上的树叶。我想做递归,但我不能接受零以外的输出。谢谢 public int countLeftChildren() { if (nodex != null) { if(nodex.left != null) { nodex = nodex.getLeft(); countLeftChildren(); } if(nodex.right != nu
public int countLeftChildren() {
if (nodex != null) {
if(nodex.left != null) {
nodex = nodex.getLeft();
countLeftChildren();
}
if(nodex.right != null) {
nodex = nodex.getRight();
countLeftChildren();
}
if(nodex.left == null && nodex.right == null && nodex==nodex.getParent().getLeft()) {
countLeftChildren++;
}
}
我想您应该将
nodex.getParent().getRight()==null
替换为nodex.getParent().getLeft()==nodex
,以确定当前节点实际上是左子节点。是否也有一个合适的孩子应该是无关紧要的
然而,你的方法有点奇怪。以下是我编写代码的方式:
class MyNode {
...
public int countLeftChildren() {
int cnt = 0;
if(left != null) {
cnt += left.countLeftChildren();
}
if(right != null) {
cnt += right.countLeftChildren();
}
if(left == null && right == null && getParent().left ==this){
cnt = 1;
}
return cnt;
}
}
您正在为节点使用单个变量
nodex
。这会导致意外行为:算法不会遍历整个树,而是遍历树的最左侧路径。除非路径末端的叶子的父级没有正确的子级,否则该算法将始终导致0。除此之外,由于缺少最后一条return语句(所有return语句都在if子句中),这段代码甚至无法编译。对于此类问题,您必须使用另一种方法:
countLeafsLeft(node n)
if n == NULL
return 0
//this node is a leaf and the left child of it's parent
if n.left == NULL AND n.right == NULL AND n.parent != NULL AND n.parent.left == THIS
return 1
int tmp = 0
if n.left != NULL
tmp += countLeafsLeft(n.left)
if n.right != NULL
tmp += countLeafsRight(n.right)