// 二叉树前序遍历
function loop(root) {
if(!root) return;
console.log(root.value);
loop(root.left);
loop(root.right);
}
// 二叉树广度遍历(自上而下)
function levelLoop(root) {
if(!root) return [];
const queue = [root];
const results = [];
while(queue.length) {
let len = queue.length;
const currValueList = []
while(len--) {
const cur = queue.shift();
currValueList.push(cur.value);
cur.left && queue.push(cur.left);
cur.right && queue.push(cur.right)
}
results.push(currValueList)
}
return results;
}
// 二叉树广度遍历(自下而上)
function levelLoop(root) {
if(!root) return [];
const queue = [root];
const results = [];
while(queue.length) {
let len = queue.length;
const currValueList = []
while(len--) {
const cur = queue.shift();
currValueList.push(cur.value);
cur.left && queue.push(cur.left);
cur.right && queue.push(cur.right)
}
results.unshift(currValueList) // 只修改这一条即可
}
return results;
}
// 之字形遍历二叉树
function levelLoop(root) {
if(!root) return [];
const res = []
const queue = [root];
let level = 1; // 用level控制从哪个方向push
while(queue.length) {
let len = queue.length;
const curValueList = [];
while(len--) {
let cur = queue.shift();
level % 2 === 0 ? curValueList.unshift(cur.value): curValueList.push(cur.value);
cur.left && queue.push(cur.left);
cur.right && queue.push(cur.right);
}
level++;
res.push(curValueList);
}
return res;
}
// 遍历N叉树
function levelLoop(root) {
if(!root) return [];
const res = []
const queue = [root];
while(queue.length) {
let len = queue.length;
const curValueList = [];
while(len--) {
let cur = queue.shift();
curValueList.push(cur.value);
queue.push(...cur.children); // 将所有的孩子push进去
}
res.push(curValueList);
}
return res;
}
// 二叉树右视图(写法一)
function levelLoop(root) {
if(!root) return [];
const res = []
const queue = [root];
while(queue.length) {
let len = queue.length;
const curValueList = [];
while(len--) {
let cur = queue.shift();
curValueList.push(cur.value);
cur.left && queue.push(cur.left);
cur.left && queue.push(cur.left);
}
res.push(curValueList.pop()); // 只收集每一层的最后一个
}
return res;
}
// 二叉树右视图(写法二)
function levelLoop(root) {
if(!root) return [];
const res = []
const queue = [root];
while(queue.length) {
let len = queue.length;
let curValue;
while(len--) {
let cur = queue.shift();
curValue = cur.value;
cur.left && queue.push(cur.left);
cur.left && queue.push(cur.left);
}
res.push(curValue); // 只收集每一层的最后一个
}
return res;
}
二叉树相关遍历
最新推荐文章于 2024-10-30 18:24:25 发布