深度优先遍历(DFS)分为先中后序遍历,在上一博文中已写到。
层次遍历即宽度优先遍历(BFS),是指按照从上到下的层级,每层从左到右来遍历二叉树。
/**
* 层次遍历 又名宽度优先遍历
* 从上到下每一层地从左到右依次遍历
* 如:
* 1
* / \
*6 2
* / \
* 3 4
* / \
* 7 5
* 遍历结果:1,6,2,3,4,7,5
* 方法:使用队列(头进尾出)
*/
printTreeInWidth(head: TNode) {
let quene = [];
quene.unshift(head);
while (quene.length != 0) {
let top = quene.pop(); //1.从队列中弹出一个节点
console.log(top.value); //2.打印
if (top.left) quene.unshift(top.left); //如果有 它的左子节点入列
if (top.right) quene.unshift(top.right); //如果有 它的右子节点入列
}
}
延伸:求一棵二叉树的宽度
/**
* 求一棵二叉树的宽度(最大宽度)
* 如:
* 1
* / \
* 6 2
* / / \
* 9 3 4
* / \
* 7 5
* 的最大宽度为3
*/
getTreeMaxWidth(head:TNode){
let quene = []; //使用一个队列
quene.unshift(head);
let curLevEnd = head; //当前层最右边的节点
let nextLevEnd = null; //下一层最右边的节点
let curLevNodes = 0; //当前层所发现的节点数
let max = 0; //最大宽度
while(curLevEnd != null){
let top = quene.pop();
if(top.left != null){
quene.unshift(top.left);
nextLevEnd = top.left;
}
if(top.right != null){
quene.unshift(top.right);
nextLevEnd = top.right;
}
curLevNodes++;
if(top == curLevEnd){
max = Math.max(max,curLevNodes);
curLevEnd = nextLevEnd;
nextLevEnd = null;
curLevNodes = 0;
}
}
return max;
}