目录
深度优先 DFS 广度优先 BFS
前序、中序、后序遍历 层序遍历
前序、中序、后序
function preorderTraversal (root) {
if (!root) return [];
const res = [];
function traversal (root) {
res.push(root.val); // 中序inorderTraversal 放中间,后序postorderTraversal 放最后
root.left && traversal(root.left);
root.right && traversal(root.right);
}
traversal(root);
return res;
}
层序遍历
结果为一维数组,利用栈:
function levelOrder (root) {
if (!root) return [];
const queue = [root];
const res = [];
while (queue.length) {
const node = queue.shift();
res.push(node.val);
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
return res;
}
结果是按层次存储的二维数组,使用迭代:
function levelOrder (root) {
if (!root) return [];
const res = [];
// 记录深度depth
function traversal (root, depth) {
if (!res[depth]) res[depth] = [];
res[depth].push(root.val);
root.left && traversal(root.left, depth + 1);
root.right && traversal(root.right, depth + 1);
}
traversal(root, 0);
return res;
}
二叉树的最大深度
function maxDepth (root) {
if (!root) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}