简体   繁体   English

在二叉搜索树中插入问题

[英]Inserting in a Binary search tree issues

I am getting confused on my binary search algorithm. 我对自己的二进制搜索算法感到困惑。 I have to insert the following integers into an empty binary tree in the given order using put(): 4,1,3,5,2. 我必须使用put()以给定的顺序将以下整数插入到空的二叉树中:4,1,3,5,2。 Im not 100 percent sure if I went about the right way in doing this. 我不能百分百确定自己是否采取了正确的方法。 Here is what I did.. My main part of confusion came up when I had to insert the 2. I just want to make sure I am doing this correctly. 这就是我所做的。.当我不得不插入2.时,我的主要困惑出现了。我只是想确保自己正确执行了此操作。 Thanks all. 谢谢大家

       4
      / \
     1   5
    /\   
      3
      /
     2

You are spot on, 2 < 4 and 2 > 1 and finally 2 < 3 您位于2 <42> 1 ,最后是2 <3

The Rules for Binary Search Tree Insertion are as follows: 二进制搜索树插入规则如下:

If the key to insert is smaller than the current value , insert the key into the current values left subtree. 如果要插入的键小于当前值 ,则将键插入到当前值左侧子树中。

If the key to insert is larger than the current value , insert the key into the current values right subtree. 如果要插入的键大于当前值 ,则将键插入到当前值的右子树中。

If the key is a duplicate value you will not insert. 如果键是重复值 ,则不会插入。

It may seem to you that your answer is wrong because you may think it looks weird to you as a human to have 2 as a child of 3. Dont worry about that oddity. 在您看来,您的答案是错误的,因为您可能认为对于2作为3的孩子来说,对于人类来说似乎很奇怪。 Just trust the algorithm, follow the rules all the time, and your insertion will work. 只要相信算法,就一直遵循规则,插入就可以了。

I am posting a link you should take a look at. 我发布了一个链接,您应该看看。 It gives an excellent visualization of many data structures, and will help you if you run into a problem like this again. 它可以很好地可视化许多数据结构,如果再次遇到类似问题,将为您提供帮助。 The site allows you to build your own binary search tree in whatever order you would like to insert. 该站点允许您以想要插入的顺序构建自己的二进制搜索树。

As a side note: The site also offers many other data structure visualizations should you have a similar question on a different data structure in the future. 附带说明:如果您将来对其他数据结构有类似的问题,则该站点还提供许多其他数据结构可视化。

Binary Search Tree Visualization 二叉搜索树可视化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM