二叉树
借鉴:http://www.conardli.top/docs/dataStructure/
完全二叉树
class Node { constructor(data, left, right){ this.data = data this.left = left this.right = right } show() { console.log(this.data) } } class Tree{ constructor(){ this.root = null } insert(data){ let node = new Node(data, null, null) if(!this.root){ this.root = node return } let current = this.root // console.log(JSON.stringify(current), 'current') while(current){ if(current.data < data) { if(!current.right){ current.right = node return } current = current.right }else{ if(!current.left){ current.left = node return } current = current.left } } } preOrder(node){ if(node){ node.show() this.preOrder(node.left) this.preOrder(node.right) } } middleOrder(node){ if(node){ this.middleOrder(node.left) node.show() this.middleOrder(node.right) } } lasterOrder(node){ if(node){ this.lasterOrder(node.left) this.lasterOrder(node.right) node.show() } } getDeep(node, deep = 0) { if(!node){ return deep } deep ++ let lDeep = this.getDeep(node.left, deep) let rDeep = this.getDeep(node.right, deep) return Math.max(lDeep, rDeep) } } var t = new Tree(); t.insert(3); t.insert(8); t.insert(1); t.insert(2); t.insert(10); t.insert(5); t.insert(6); // console.log(t.preOrder(t.root)) // console.log(t.middleOrder(t.root)) // console.log(t.lasterOrder(t.root)) console.log(t.getDeep(t.root))
根据前序遍历和中序遍历的接口,推出二叉树
function reConstructBinaryTree(pre, vin) { if(pre.length === 0){ return null; } if(pre.length === 1){ return new Node(pre[0]); } const value = pre[0]; const index = vin.indexOf(value); const vinLeft = vin.slice(0,index); const vinRight = vin.slice(index+1); const preLeft = pre.slice(1,index+1); const preRight = pre.slice(index+1); const node = new Node(value); node.left = reConstructBinaryTree(preLeft, vinLeft); node.right = reConstructBinaryTree(preRight, vinRight); return node; } var list = reConstructBinaryTree([1,2,4,7,3,5,6,8], [4,7,2,1,5,3,8,6])