binary search tree

blov · · 316 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I am trying to learn data structures using Go and to be a better programmer in general. </p> <p>I was curious why some implementation of Binary Search Tree have root node in the struct and some don&#39;t.</p> <p>I like this blog post, <a href="http://tobin.cc/blog/bst/" rel="nofollow">http://tobin.cc/blog/bst/</a> where he declares it like this</p> <pre><code>type Node struct { key *int Left, Right,Root *Node } </code></pre> <p>then he places all the nodes in a tree object</p> <pre><code>type Tree struct { root *Node } </code></pre> <p>I seen implementations where there is no root node in Node struct and some implementations of no tree object whatsoever.</p> <p>What is a good implementation to study? A simple implementation without interfaces is preferred. And int type is fine with me.</p> <hr/>**评论:**<br/><br/>pekim: <pre><blockquote> <p>I was curious why some implementation of Binary Search Tree have root node in the struct and some don&#39;t.</p> </blockquote> <p>It&#39;s likely so that receiver functions can be used with the struct. This is an example of that in the blog article that you referenced.</p> <pre><code>func (t *Tree) Flatten() []int { ... } </code></pre></pre>joh_ng: <pre><p>As for me, i prefer the declaration of the node without root. The node added first is the root of the BST. The implementation below is done in C++</p> <p>struct Node { int key; Node* left, right;</p> <p>Node(int _key) : key(_key), left(nullptr), right(nullptr) {} };</p> <p>Node* insert(Node* currentNode, int newKey) { if (currentNode == nullptr) return new Node(newKey); else { If (newKey &lt;= currentNode-&gt;key) currentNode-&gt;left = insert(currentNode-&gt;left, newKey); else currentNode-&gt;right = insert(currentNode-&gt;right, newKey); } return currentNode; }</p> <p>void main() { /* Assuming wanna construct a simple BST as below 4 / \ 2 6</p> <p>Node with key value is 4 is root <em>/ Node</em> currentNode = insert(4); Node* root = currentNode; // the root node of BST</p> <p>currentNode = insert(currentNode, 2); currentNode = insert(currentNode, 6); }</p></pre>joh_ng: <pre><p>Oh, why auto cut off few asterisk symbol like Node* (currentNode, int newKey)</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

316 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传