js实现创建二叉树+先序遍历
生活随笔
收集整理的这篇文章主要介绍了
js实现创建二叉树+先序遍历
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
二叉树概念
1.除了最下面一层,每个节点都是父节点,每个节点都有且最多有两个子节点;
2.除了嘴上面一层,每个节点是子节点,每个节点都会有一个父节点;
3.最上面一层的节点为根节点;
图例说明:
先序遍历概念
先打印父节点,然后是左子节点(左子树),然后再打印右子节点(子树)
图例说明:
最后贴代码
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Document</title> </head> <body><script>//创建二叉树function Node(data,left,right){this.data = data;this.left = left;this.right = right;}Node.prototype.show = function(){return this.data;}function BST(){this.root = null;}BST.prototype.insert = function(data){var node = new Node(data,null,null);if(this.root == null){this.root = node;}else{var current = this.root;var parent;while(true){parent = current;if(data < current.data){current = current.left;if(current == null){parent.left = node;break;}}else{current = current.right;if(current == null){parent.right = node;break;}}}}}//二叉树先序遍历BST.prototype.perOrder = function(node){if(node){console.log(node.show() + " ");this.perOrder(node.left);this.perOrder(node.right);}}//测试数据var bst = new BST();var nums = [10,3,18,2,4,13,21,9,8,9];for(var i = 0;i < nums.length;i ++){bst.insert(nums[i]);}bst.perOrder(bst.root);</script> </body> </html>
转载于:https://www.cnblogs.com/xiaohualu/p/10308071.html
总结
以上是生活随笔为你收集整理的js实现创建二叉树+先序遍历的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 解决 WIndows,Linux 以及
- 下一篇: [CQOI2018] 异或序列