一、核心思想
1.前序
本质是中左右,对每个结点执行中左右的操作,全部结点执行完毕后,返回结果
2.中序
本质是左中右,对每个结点执行左中右的操作,全部结点执行完毕后,返回结果
3.后序
本质是左右中,对每个结点执行左右中的操作,全部结点执行完毕后,返回结果
ps:注意初始值为空的情况
二、代码实现
1.前序
let tree = {val: 1,leftChild: {val: 2,leftChild: {val: 3,leftChild: {val: 4,},rightChild: {val: 5,},},rightChild: {val: 6,},},rightChild: {val: 7,leftChild: {val: 8,},rightChild: {val: 9,leftChild: {val: 10,},},},
};
/*** 前序遍历二叉树* @param {Array} root 传入数组* @return {Array} list 返回深度遍历二叉树数组结果*/
function preOrder(root){let list = []if (!root) {return []}function order(root){list.push(root.val)if (root.leftChild) {order(root.leftChild)}if (root.rightChild) {order(root.rightChild)}}order(root)return list
}
console.log(preOrder(tree))
// [
// 1, 2, 3, 4, 5,
// 6, 7, 8, 9, 10
// ]
2.中序
let tree = {val: 1,leftChild: {val: 2,leftChild: {val: 3,leftChild: {val: 4,},rightChild: {val: 5,},},rightChild: {val: 6,},},rightChild: {val: 7,leftChild: {val: 8,},rightChild: {val: 9,leftChild: {val: 10,},},},
};
/*** 中序遍历二叉树* @param {Array} root 传入数组* @return {Array} list 返回深度遍历二叉树数组结果*/
function midOrder(root){let list = []if (!root) {return []}function order(root){if (root.leftChild) {order(root.leftChild)}list.push(root.val)if (root.rightChild) {order(root.rightChild)}}order(root)return list
}
console.log(midOrder(tree))
// [
// 4, 3, 5, 2, 6,
// 1, 8, 7, 10, 9
// ]
3.后序
let tree = {val: 1,leftChild: {val: 2,leftChild: {val: 3,leftChild: {val: 4,},rightChild: {val: 5,},},rightChild: {val: 6,},},rightChild: {val: 7,leftChild: {val: 8,},rightChild: {val: 9,leftChild: {val: 10,},},},
};
/*** 后序遍历二叉树* @param {Array} root 传入数组* @return {Array} list 返回深度遍历二叉树数组结果*/
function afterOrder(root){let list = []if (!root) {return []}function order(root){if (root.leftChild) {order(root.leftChild)}if (root.rightChild) {order(root.rightChild)}list.push(root.val)}order(root)return list
}
console.log(afterOrder(tree))
// [
// 4, 5, 3, 6, 2,
// 8, 10, 9, 7, 1
// ]