二叉树(Binary Tree)每个节点最多有两个子节点的树型数据结构。
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
深度优先顾名思义就是先纵向搜索,在进入下一个兄弟节点之前,尽可能的向下搜索每一个子节点。 该算法从根节点开始(在图的情况下选择一些任意节点作为根节点)并在回溯之前尽可能地沿着每个分支进行探索。
function preOrder(root) {
if (!root) {
return;
}
// do something
// console.log(root.val)
preOrder(root.left);
preOrder(root.right);
}
function preOrderWithoutRecursion(root) {
const stack = [];
let node = root;
while (node || stack.length > 0) {
if (node) {
// do something
// console.log(node.val);
stack.push(node);
node = node.left;
} else {
node = stack.pop().right;
}
}
}
function inOrder(root) {
if (!root) {
return;
}
inOrder(root.left);
// do something
// console.log(root.val);
inOrder(root.right);
}
function inOrderWithoutRecursion(root) {
const stack = [];
let node = root;
while (node || stack.length > 0) {
if (node) {
stack.push(node);
node = node.left;
} else {
const lastNode = stack.pop();
// do something
// console.log(lastNode.val);
node = lastNode.right;
}
}
}
function postOrder(root) {
if (!root) {
return;
}
postOrder(root.left);
postOrder(root.right);
// do something
// console.log(root.val);
}
function postOrderWithoutRecursion(root) {
if (!root) {
return;
}
const stack = [];
let node = root;
let last = node;
stack.push(node);
while (stack.length > 0) {
node = stack[stack.length - 1];
if (
(!node.left && !node.right) ||
(!node.right && last === node.left) ||
last === node.right
) {
// doing something
// console.log(node.val);
last = node;
stack.pop();
} else {
if (node.right) {
stack.push(node.right);
}
if (node.left) {
stack.push(node.left);
}
}
}
}
function bfs(root) {
if (!root) {
return;
}
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
// do something
// console.log(node.val)
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
}