【问题标题】:Inserting binary tree node插入二叉树节点
【发布时间】:2016-04-06 06:39:36
【问题描述】:

我正在尝试向我的树中插入一个节点。

   public void addNode(BinaryTree playerOrTeamLeaf) {
            if (left == null) {
                left = new BinaryTree(playerOrTeamLeaf);
                return;
            } else if (left != null) {
                left.addNode(playerOrTeamLeaf);
            }

            if (right == null) {
                right = new BinaryTree(playerOrTeamLeaf);
                return;
            } else if (right != null) {
                right.addNode(playerOrTeamLeaf);
                return;
            }
        }

如您所知,这是一棵有问题的树。这就是树目前的样子。

       a
     b   
   d   
 e  

如果条件先运行,您可以告诉左边,这就是导致问题的原因。

我的目标是一棵漂亮的平等树。我知道问题出在哪里,我们有一个大小为 4 的树 IE。

    A
  B   
C

我的逻辑代码沿着这个伪代码的行运行(这是第 5 片叶子的插入),它从“A”开始,我们插入“D”:

 if left is null then left is equal to a new Node then return; | left = 'B'
 else if left is not null
 go to left object add method and pass in 'E';
     if left is null then left is equal to a new Node then return; | left = 'C'      else if left is not null
     go to left object add method and pass in 'E';
                   if left is null then left is equal to a new Node then | //seee below

所以这让我的树看起来像这样。

      A
    B   
  D
E

我知道它这样做是因为第一个 if 语句,但如何解决这个问题的逻辑让我感到困惑。我试图交换左右语句,但这只是翻转了树生长的一侧。

我知道这本质上是一个链接列表,但我不确定如何才能解决这个问题。

有什么想法吗?

【问题讨论】:

  • 你只是想让树保持平衡,还是根据“键”对树进行排序?
  • 想要的树是什么样的?我不知道你想建造什么样的树。您当前的逻辑似乎只会将节点添加到树的左侧。
  • 基本上是一棵相等的树,底部有 8/16/32 个节点

标签: java binary-tree


【解决方案1】:

一般的想法是这样的:

BinaryTree insert(Binary tree, int value) {
    if (tree == null) {
        return new BinaryTree(value);
    }
    if (value < tree.value) {
        tree.left = insert(tree.left, value);
    } else if (value > tree.value) {
        tree.right = insert(tree.right, value);
    }
    return tree;
}

BinaryTree tree = null;
tree = insert(tree, 19);
tree = insert(tree, 7);
tree = insert(tree, 23)
tree = insert(tree, 11);

           19
           /\
          7  23
           \
            11

         7 11 19 23

这样可以确保在一个地方插入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2018-05-03
    • 2022-01-13
    相关资源
    最近更新 更多