二叉树

tech2024-11-20  4

let arr=[5,1,2,6,5] function Node(val){ this.val=val; this.left=null; this.right=null; this.addLeft=function(node){ this.left=node; }; this.addRight=function(node){ this.right=node; } } let root=new Node(arr.shift()); arr.map(item=>{ addNode(root,item); }) //自动生成二叉查找树 function addNode(node,val){ if(node==null) return; if(val<=node.val){ if(node.left){ addNode(node.left,val); } else{ node.left=new Node(val); } } else { if(node.right){ addNode(node.right,val); } else { node.right=new Node(val); } } } //前序遍历 function beginCon(node){ if(node==null)return; console.log(node.val); beginCon(node.left); beginCon(node.right); } //中序遍历 function centerCon(node){ if(node==null)return; beginCon(node.left); console.log(node.val); beginCon(node.right); } //获取高度 function getHeight(node){ if(node==null)return 0; else { let left = getHeight(node.left); let right = getHeight(node.right); let deep= left; if(deep<right)deep=right; return deep+1; } } //获取树里最大值 function getMax(node){ if(node==null) return -1; let left=getMax(node.left); let right=getMax(node.right); let mid = node.val; let max =left; if(right>max){ max=right; } if(mid>max){ max=mid; } return max; } beginCon(root); console.log('---------------'); centerCon(root); console.log('---------------'); console.log('高度:',getHeight(root)) console.log('最大值:',getMax(root))
最新回复(0)