1.先序遍历:
先序遍历算法口诀:
1.访问根节点
2.对根节点的左子树进行先序遍历
3.对根节点的右子树进行先序遍历
实例:
const bt = {
val: 1,
left: {
val: 2,
left: {
val: 4,
left: null,
right: null
},
right: {
val: 5,
left: null,
right: {
val: 7,
left: null,
right: null
}
}
},
right: {
val: 3,
left: null,
right: {
val: 6,
left: null,
right: null
}
}
}
const preorder = (root) => {
if (!root) { return; }
console.log(root.val);
preorder(root.left);
preorder(root.right);
}
preorder(bt);
2.中序遍历:
中序遍历算法口诀:
1.对根节点的左子树进行中序遍历
2. 访问根节点
3.对根节点的右子树进行中序遍历
实例:
const bt = {
val: 1,
left: {
val: 2,
left: {
val: 4,
left: null,
right: null
},
right: {
val: 5,
left: null,
right: {
val: 7,
left: null,
right: null
}
}
},
right: {
val: 3,
left: null,
right: {
val: 6,
left: null,
right: null
}
}
}
const inorder = (root) => {
if (!root) { return; }
inorder(root.left);
console.log(root.val);
inorder(root.right);
}
inorder(bt);
3.后序遍历:
后序遍历算法口诀:
1.对根节点的左子树进行后序遍历
2. 对根节点的右子树进行后序遍历
3. 访问根节点
实例:
const bt = {
val: 1,
left: {
val: 2,
left: {
val: 4,
left: null,
right: null
},
right: {
val: 5,
left: null,
right: {
val: 7,
left: null,
right: null
}
}
},
right: {
val: 3,
left: null,
right: {
val: 6,
left: null,
right: null
}
}
}
const postorder = (root) => {
if (!root) { return; }
postorder(root.left);
console.log(root.val);
postorder(root.right);
}
postorder(bt);