标签:for next dex int func result 技术 val isa
还原二叉树
function preMid(pre,mid){ if(pre.length == 0 || mid.length == 0){ return null } var root = pre[0] //前序第一个是根节点 //获取根节点在中序中的索引值 var rootMidIndex = mid.indexOf(root) //划分中序左边的节点 var leftMid = mid.slice(0,rootMidIndex) //划分中序右边的节点 var rightMid = mid.slice(rootMidIndex + 1) //划分前序左边的节点 var leftPre = pre.slice(1, leftMid.length + 1) //划分前序右边的节点 var rightPre = pre.slice(leftMid.length + 1) var left = preMid(leftPre,leftMid) var right = preMid(rightPre,rightMid) var node = new Node(pre[0],left,right) return node }
function aftMid(aft,mid){ if(aft.length == 0 || mid.length == 0){ return null } var root = aft[aft.length - 1] //后序最后一个是根节点 //获取根节点在中序中的索引值 var rootMidIndex = mid.indexOf(root) //划分中序左边的节点 var leftMid = mid.slice(0,rootMidIndex) //划分中序右边的节点 var rightMid = mid.slice(rootMidIndex + 1) //划分后序左边的节点 var leftAft = aft.slice(0, leftMid.length) //划分后序右边的节点 var rightAft = aft.slice(leftMid.length,aft.length -1) var left = aftMid(leftAft,leftMid) var right = aftMid(rightAft,rightMid) var node = new Node(aft[aft.length -1],left,right) return node }
二叉树深度查找
function deepFirstSearch(root,targetValue){ if(!root) return false if(root.value === targetValue) return true; var searchLeft = deepFirstSearch(root.left,targetValue); var searchRight = deepFirstSearch(root.right,targetValue); return searchLeft || searchRight }
二叉树广度查找
function breadthFirstSearch(nodes,targetValue){ nodes = Array.isArray(nodes) ? nodes :[nodes]; if(nodes.length == 0) return false; var nexts = []; for(let i = 0; i < nodes.length;i++){ if(nodes[i].value === targetValue){ return true }else{ if(nodes[i].left){ nexts.push(nodes[i].left) } if(nodes[i].right){ nexts.push(nodes[i].right) } } } return breadthFirstSearch(nexts,targetValue) }
层层打印二叉树
function Print(node){ if(!node) return [];
let root = [node];
let result = []; //最后返回的集合
while(root.length){
let len = root.length;
let temparr = []; //同级层集合
for(let i = 0; i < len ; i++){
let temp = root.shift();
temparr.push(temp.value)
if(temp.left) root.push(temp.left);
if(temp.right) root.push(temp.right);
}
result.push(temparr)
}
return result; }
对比两颗二叉树区别
function diff(orginRoot,newRoot){ var result = []; if(!orginRoot && !newRoot){ return [] }else if(!orginRoot && newRoot){ result.push({ type:"新增", orginNode: orginRoot, newNode: newRoot }) }else if(orginRoot && !newRoot){ result.push({ type:"删除", orginNode: orginRoot, newNode: newRoot }) }else if(orginRoot.value !== newRoot.value){ reslut.push({ type:"修改", orginNode: orginRoot, newNoe : newRoot }) var result1 = diff(orginRoot.left,newRoot.left); var reslut2 = diff(orginRoot.right,newRoot.right); result = [..result,...result1,...result2] }else{ var result1 = diff(orginRoot.left,newRoot.left) var reslut2 = diff(orginRoot.right,newRoot.right); result = [..result,...result1,...result2] } return result }
标签:for next dex int func result 技术 val isa
原文地址:https://www.cnblogs.com/wangyisu/p/13324510.html