我试图消除所有的叶子。我知道叶子有没有孩子,这是我到目前为止所。
公共无效removeLeaves(二叉树N){
如果(n.left == NULL和放大器;&安培; n.right == NULL){
N = NULL;
}
如果(n.left!= NULL)
removeLeaves(n.left);
如果(n.right!= NULL)
removeLeaves(n.right);
}
解决方案
这是容易得多,如果你打破下来是这样的:
公共无效removeLeaves(二叉树N){
如果(n.left!= NULL){
如果(n.left.isLeaf()){
n.removeLeftChild();
} 其他 {
removeLeaves(n.left);
}
}
//重复的右子
// ...
}
传递isLeaf
, removeLeftChild
和 removeRightChild
应该是微不足道实现。
I'm trying to remove all of the leaves. I know that leaves have no children, this is what I have so far.
public void removeLeaves(BinaryTree n){
if (n.left == null && n.right == null){
n = null;
}
if (n.left != null)
removeLeaves(n.left);
if (n.right != null)
removeLeaves(n.right);
}
解决方案
It's much easier if you break this down like this:
public void removeLeaves(BinaryTree n){
if (n.left != null) {
if (n.left.isLeaf()) {
n.removeLeftChild();
} else {
removeLeaves(n.left);
}
}
// repeat for right child
// ...
}
isLeaf
, removeLeftChild
and removeRightChild
should be trivial to implement.
上一篇:如何实现动态二进制搜索n个元素的搜索和INSERT操作如何实现、元素、操作、动态
下一篇:byte []的任意大小转换为BigInteger的[],然后安全地转换回一模一样的byte [],任何线索?转换为、线索、大小、安全