Javascript实现从小到大的数组转换成二叉搜索树
时间:2021-07-19 07:59:17|栏目:JavaScript代码|点击: 次
废话不多说了,直接给大家贴代码了,具体代码如下所示:
var Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var Tree = createTree(Array); console.log(Tree); // 构造一个节点 function Node(nodeData, leftData, rightData) { this.nodeData = nodeData; this.leftData = leftData; this.rightData = rightData; } // 每次取中点作为根节点,向左和向右递归 function createTree(array) { if (array.length <= 0) { return null; } else { var mid = parseInt(array.length / 2); var node = new Node(array[mid], null, null); var leftArray = array.slice(0 , mid); var rightArray = array.slice(mid + 1 , array.length ); node.leftData = createTree(leftArray); node.rightData = createTree(rightArray); return node; } }