【问题标题】:Adding (and Finding) an element to a binary tree (NOT BST)向二叉树添加(和查找)元素(非 BST)
【发布时间】:2013-11-13 02:51:00
【问题描述】:

所以我试图将一个元素放在 java 中的二叉树(不是搜索树)中。我到处寻找,我所看到的只是将其插入二叉 search 树的算法(我想要一个简单的二叉树)。给定父节点的值,我需要设置左右子节点。我的计划是这样的:

public void addLeft(E elem, E parentVal) {
//Find node with parentVal
//Create node with element elem (call it newNode)
//Set the left child of the node with parentVal as newNode
}

最后两个步骤相当简单,所以我真正的问题是找到具有给定值的节点。 在搜索树中,这很容易,但在普通的二叉树中,我不知道该怎么做。我知道这不会有效率;据我所知,要将元素添加到普通二叉树中的给定节点,我们必须遍历整个树才能找到该节点。关于如何做到这一点的任何建议?假设没有数字重复(所有节点都有一个唯一元素)。我已将此标记为算法/伪代码,所以我只需要一个基本的想法就可以开始(尽管代码也很受欢迎)。

【问题讨论】:

  • 在二叉(非搜索)树中,您通过遍历树的所有节点进行搜索,并在找到结果/访问过所有节点时停止。如果没有其他问题,如果您可以使用列表获得相同的性能,那么添加树的复杂性是没有意义的。
  • @SJuan,是的,您在节点上运行,但是如何?首先遍历左子树,一旦到达最左子树的末端,该怎么办?

标签: java algorithm binary-tree pseudocode


【解决方案1】:

这是一种递归遍历树并在找到parentVal 时停止的简单方法:

// returns true if the element has been added to this subtree
public boolean addLeft(E elem, E parentVal) {
    if (this.equals(parentVal)) {
        //Create node with element elem (call it newNode)
        //Set the left child of the node with parentVal as newNode
        return true;
    } else if (leftChild != null && leftChild.addLeft(elem, parentVal)) {
        return true;
    } else {
        return rightChild != null && rightChild.addLeft(elem, parentVal);
    }
}

这是假设一个节点可以通过leftChild/rightChild访问它的子节点。

【讨论】:

  • 这不是指树而不是节点吗?
  • 为了将它用于整个树,您只需在根节点上调用它。
【解决方案2】:

Google code 找到这个,在 github 搜索带我到这个Java implementation

另一个快速的原始编写实现是python implementation of Binary tree。链接的标题具有误导性,但请检查整个文章。

来自这里的链接是一个高级psuedo。,

class Node:
    ...
    def insert(self, data):
        """
        Insert new node with data

        @param data node data object to insert
        """
        if data < self.data:
            if self.left is None:
                self.left = Node(data)
            else:
                self.left.insert(data)
        else:
            if self.right is None:
                self.right = Node(data)
            else:
                self.right.insert(data)

【讨论】:

  • 你知道在这种情况下 self 指的是什么吗?是根,还是有问题的节点,还是什么?
猜你喜欢
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多