[Algorithm] Construct a Binary Tree and Binary Search
and Tree search Binary ALGORITHM Construct
2023-09-14 08:59:15 时间
function createNode(value) { return { value, left: null, right: null }; } function BinaryTree(val) { return { root: null, nodes: [], add(val) { const node = createNode(val); if (!this.root) { this.root = node; } else { this.downShift(node); } this.nodes.push(node); }, downShift(node) { let value = node.value; let current = this.root; while (current) { if (value > current.value) { if (!current.right) { current.right = node; break; } else { current = current.right; } } else { if (!current.left) { current.left = node; break; } else { current = current.left; } } } }, size() { return this.nodes.length; }, search(target) { let found = false; let current = this.root; while (current) { if (target > current.value) { if (!current.right) { return "Not Found"; } current = current.right; } else if (target < current.value) { if (!current.left) { return "Not Found"; } current = current.left; } else { found = true; break; } } return found; } }; } const t = new BinaryTree(); t.add(4); t.add(7); t.add(3); t.add(1); t.add(9); t.add(2); t.add(5); console.log(t.search(8));
About how to traverse binary tree, can refer this post.
相关文章
- [Java Spring Data] Query method clauses and expressions
- [Machine Learning] Simplified Cost Function and Gradient Descent
- [XState] Invoke Callbacks to Send and Receive Events from a Parent XState Machine
- [RxJS] Use RxJS mergeMap to map and merge high order observables
- LeetCode:105_Construct Binary Tree from Preorder and Inorder Traversal | 根据前序和中序遍历构建二叉树 | Medium
- [Swift] Storyboard outlet and action
- Efficient and Accurate Arbitrary-Shaped Text Detection with Pixel Aggregation Network(利用像素聚合网络进行高效准确的任意形状文本检测)
- Atitit.软件的建模种类and 建模语言选型and UML???
- 【Codeforces 459D】Pashmak and Parmida's problem
- 【Codeforces 639B】Bear and Forgotten Tree 3
- 【Henu ACM Round#16 F】Om Nom and Necklace
- 【codeforces 764C】Timofey and a tree
- 【codeforces 514E】Darth Vader and Tree
- 可解释性nlp 万能model (left_and_right 最终版)
- 完美解决TensorFlow-gpu报错问题Could not load dynamic library ‘libnvinfer.so.6’ and ‘libcudart.so.11.0’
- 【线代&NumPy】第八章 - 特征值和特征向量 | Eigenvalue and Eigenvector | 简述并提供代码