如何删除二进制树的叶子?叶子

2023-09-11 06:22:51 作者:先爱的人注定遍体凌伤

我试图消除所有的叶子。我知道叶子有没有孩子,这是我到目前为止所。

 公共无效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.