我使用以下方法(使用宽度优先遍历算法)以连续顺序将项添加到二叉树中。
例如,如果我有
A
/ \
B C
/
D
我希望下一个补充是:
A
/ \
B C
/ \
D E
我的问题在于我不知道如何正确地返回这个值。我知道当我们遇到第一个空节点时,我们会在那里插入值,但是我们要把它插入到什么中呢?如果我们将它插入到从队列中获得的二叉树中,那就是根的子树(或者我们试图添加的树),所以返回的不是完整的树。
下面是我的代码:
public static <T> BinaryTree<T> addToTree(BinaryTree<T>
我正在尝试从排序列表中创建一棵树,以便以后可以搜索它。
问题是
如果找到,我必须返回数字的索引,否则我返回-1,所以我创建了这个函数。
data Tree e i = Leaf e i | Node (Tree e i) e i (Tree e i)
occurs :: Int -> Tree Int Int -> Int
occurs x (Leaf y i) | x == y = i
| otherwise = -1
occurs x (Node l y i r) | x == y = i
我最近学到了二叉树,并决定练习一下。我认为我非常理解指针和引用参数,但随后我看到了以下代码:
void doubleTree(struct node* node) {
struct node* oldLeft;
if (node==NULL) return;
// do the subtrees
doubleTree(node->left);
doubleTree(node->right);
// duplicate this node to its left
oldLeft = node->left;
这是维基百科上关于BST的一些代码:
# 'node' refers to the parent-node in this case
def search_binary_tree(node, key):
if node is None:
return None # key not found
if key < node.key:
return search_binary_tree(node.leftChild, key)
elif key > node.key:
return s
我试图使用函数insert_elements编写代码,在二进制搜索树中插入节点。在我的教科书里,这个函数的代码是-
struct node *root;
int main(){
root = insert_elements(root, val); // val is the value to be inserted
return 0;
}
struct node *insert_elements(struct node *root, int val){
// code to insert node
return root;
}
我不明白为什么我们要返回函数ins
优先级队列:基本操作:插入删除(Delete minumum元素)
目标:为上述功能提供高效的运行时间或增长顺序。
通过:实现优先级队列:
Linked List: Insertion will take o(n) in case of insertion at end o(1) in case of
insertion at head.
Delet (Finding minumum and Delete this ) will take o(n)
BST:
Insertion/Deltion of minimum = In av
我对我的Binary Search Tree类的contains方法感到困惑。
public boolean contains(Object o) {
if (o == null)
{
throw new NullPointerException("Null Items are not allowed in the tree");
}
if (root.item.equals(o))
{
return true;
}
return false;
}
这是我的标题:
public class
排序算法可以描述如下:
1.从数组数据创建二进制搜索树.
(对于多次发生,当前节点的增量发生变量)
2.无序地遍历BST。。
(无序遍历将返回数组中元素的排序顺序)。
3.按顺序遍历每个节点,用当前节点值覆盖当前索引处的数组元素(索引从0开始)。
下面是一个相同的Java实现:
节点类的结构
class Node {
Node left;
int data;
int occurence;
Node right;
}
无序函数(返回类型为int,只用于在每次调用时获得正确的索引,它们没有其他用途)
public int inorder(Node root,int[
我有一个按A-Z顺序排列的字符串数组。我想知道对它们进行排序以获得平衡的二进制搜索树的最好方法。我最初的想法是将数组分为前半部分和后半部分,然后分别对它们进行排序。
难道我不能使用递归的方式将其一分为二,以获得树的下一个节点吗?我只是现在还不能完全理解它,我想我应该问问是否有人有什么想法。来引导我朝着正确的方向前进,或者提供一些例子。谢谢!
我正在使用我自己的BinaryTree类和BinaryTreeNode类。编辑:
public class BinaryTree {
private BinaryTreeNode root;
public void insert(String text)
我正在为类编写二进制搜索树作业,对于这个函数,我需要遵循我教授的伪代码。不幸的是,我不确定一个具体的细节,而她拒绝澄清。
链接到伪代码在这里:
SUBROUTINE insert(current, parent, node)
IF current is null
IF parent is null
root = node
ELSE
ID node.value < parent.value
parent.left = node
ELSE