如何删除二进制树的叶子? [英] How do I remove the leaves of a binary tree?

查看:275
本文介绍了如何删除二进制树的叶子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何删除二进制树的叶子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆