[Algorithm] Binary tree: Level Order Traversal
Tree Binary order level ALGORITHM Traversal
2023-09-14 09:00:48 时间
function Node(val) { return { val, left: null, right: null }; } function Tree() { return { root: null, addLeft(val, root) { const newNode = Node(val); root.left = newNode; return newNode; }, addRight(val, root) { const newNode = Node(val); root.right = newNode; return newNode; }, levelOrder(root, visitFn) { const helper = (node, visitFn) => { if (node === null) { return; } const q = new Queue(); q.push(node); while (!q.isEmpty()) { const current = q.peak(); visitFn(current.val); current.left && q.push(current.left); current.right && q.push(current.right); q.pop(); } }; helper(root, visitFn); } }; } function Queue() { return { nodes: [], push(val) { this.nodes.push(val); // O(1) }, pop() { const [first, ...rest] = this.nodes; this.nodes = rest; return first; }, peak() { return this.isEmpty() ? null : this.nodes[0]; }, isEmpty() { return this.nodes.length === 0; } }; } /** 20 14 28 10 15 24 32 4 11 21 */ const tree = new Tree(); const n1 = Node(20); tree.root = n1; const n2 = tree.addLeft(14, n1); const n3 = tree.addRight(28, n1); const n4 = tree.addLeft(10, n2); tree.addRight(15, n2); const n5 = tree.addLeft(24, n3); tree.addRight(32, n3); tree.addLeft(4, n4); tree.addRight(11, n4); tree.addLeft(21, n5); tree.levelOrder(tree.root, x => console.log(x)); //20,14,28,10,15,24,32,4,11,21
相关文章
- Minimum Depth of Binary Tree
- Leetcode 之Binary Tree Postorder Traversal(47)
- [Algorithm] 94. Binary Tree Inorder Traversal iteratively approach
- [Algorithm] Inorder Successor in a binary search tree
- [Algorithm] Delete a node from Binary Search Tree
- 【Python 16】分形树绘制4.0(利用递归函数绘制分形树fractal tree)
- [Algorithm] 94. Binary Tree Inorder Traversal iteratively approach
- [Algorithm] Tree: Lowest Common Ancestor
- [Algorithm] Construct a Binary Tree and Binary Search
- /ui2/nwbc_nav_tr /ui2/cl_nwbc_runtime35~check_navigation_tree_cache
- B-Tree和B+Tree
- 【35.39%】【hdu 3333】Turing Tree
- 【codeforces 765E】Tree Folding
- ML之XGBoost:《XGBoost: A Scalable Tree Boosting System》的翻译与解读
- B-树(B-Tree)与二叉搜索树(BST):讲讲数据库和文件系统背后的原理(读写比较大块数据的存储系统数据结构与算法原理)...
- [LeetCode] 110. Balanced Binary Tree ☆(二叉树是否平衡)
- [LeetCode] 94. Binary Tree Inorder Traversal(二叉树的中序遍历) ☆☆☆
- PAT 1102 Invert a Binary Tree[比较简单]
- leetcode 501. Find Mode in Binary Search Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- leetcode 257. Binary Tree Paths
- leetcode 108. Convert Sorted Array to Binary Search Tree
- leetcode 543. Diameter of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- PAT 1135 Is It A Red-Black Tree 【C++版】