二叉树的层序遍历和深度遍历

深度遍历

前序遍历

function DLR(arr,root) {
if(!root) return; //遍历结束条件
arr.push(root.val) //收集结果
DLR(arr, root.left)
DLR(arr, root.right)
}

中序遍历

function LDR(arr, root) {
if(!root) return;
LDR(arr, root.left);
arr.push(root.val)
LDR(arr, root.right)
}

后序遍历

function LRD(arr, root) {
if(!root) return;
LRD(root.left)
LRD(root.right)
arr.push(root.val)
}

层序遍历

function floorPrint_queue(arr, root) {
let brr = []
if(root) {
brr.push(root)
}
while(brr.length != 0) { //当队列没有值时结束遍历
arr.push(brr[0].val); //将队头的值保留下来
if(brr[0].left != null) { //将后面需要遍历的值从队尾插入
brr.push(brr[0].left)
}
if(brr[0].right != null) {
brr.push(brr[0].right)
}
brr.shift()
}
return arr;
}

posted @ 2021-09-10 12:58  卿六  阅读(99)  评论(0编辑  收藏  举报