深度遍历
1. 前序
function preTreeSort(root) {
const result = [];
function sort(node) {
if (node !== null) {
result.push(node.val);
if (node.left !== null) {
result.push(node.left);
}
if (node.right !== null) {
result.push(node.right);
}
}
}
sort(root);
return result;
}
2. 中序
function middleSort(root) {
const result = [];
function sort(node) {
if (node !== null) {
if (node.left !== null) {
result.push(node.left);
}
result.push(node.val);
if (node.right !== null) {
result.push(node.right);
}
}
}
sort(root);
return result;
}
3. 后序
function afterSort(node) {
const result = [];
function sort(node) {
if (node !== null) {
if (node.left !== null) {
result.push(node.left);
}
if (node.right !== null) {
result.push(node.right);
}
result.push(node.val);
}
}
sort(root);
return result;
}
广度遍历
function breadth(node) {
const result = [];
node.forEach(item => {
result.push(item.val);
if (node.length) {
result.push(node.left);
}
if (node.right) {
result.push(node.eight);
}
});
if (result.lenght) {
breadth(result);
}
}