二叉树的先中后序遍历
先序遍历: 根左右
- 访问根节点
- 对根节点的左子树进行先序遍历
- 对根节点的右子树进行先序遍历
非递归版代码实现
const bt = {
val: 50,
left: {
val: 10,
left: {
val: 5,
left: null,
right: null,
},
right: {
val: 15,
left: null,
right: null,
},
},
right: {
val: 70,
left: {
val: 60,
left: null,
right: null,
},
right: {
val: 80,
left: null,
right: null,
},
},
};
const preorder = (root) => {
if (!root) { return; }
const stack = [root];
while (stack.length) {
const n = stack.pop();
console.log(n.val);
if (n.right) stack.push(n.right);
if (n.left) stack.push(n.left);
}
};
// 50 10 5 15 70 60 80
preorder(bt);
中序遍历: 左根右
- 对根节点的左子树进行中序遍历
- 访问根节点
- 对根节点的右子树进行中序遍历
非递归版代码实现
const bt = {
val: 56,
left: {
val: 22,
left: {
val: 10,
left: null,
right: null,
},
right: {
val: 30,
left: null,
right: null,
},
},
right: {
val: 81,
left: {
val: 77,
left: null,
right: null,
},
right: {
val: 92,
left: null,
right: null,
},
},
};
const inorder = (root) => {
if (!root) { return; }
const stack = [];
let p = root;
while (stack.length || p) {
while (p) {
stack.push(p);
p = p.left;
}
const n = stack.pop();
console.log(n.val);
p = n.right;
}
};
// 10 22 30 56 77 81 92
inorder(bt);
后序遍历: 左右根
- 对根节点的左子树进行后序遍历
- 对根节点的右子树进行后序遍历
- 访问根节点
非递归版代码实现
const bt = {
val: 23,
left: {
val: 16,
left: {
val: 3,
left: null,
right: null,
},
right: {
val: 22,
left: null,
right: null,
},
},
right: {
val: 45,
left: {
val: 37,
left: null,
right: null,
},
right: {
val: 99,
left: null,
right: null,
},
},
};
const postorder = (root) => {
if (!root) { return; }
const outputStack = [];
const stack = [root];
while (stack.length) {
const n = stack.pop();
outputStack.push(n);
if (n.left) stack.push(n.left);
if (n.right) stack.push(n.right);
}
while(outputStack.length){
const n = outputStack.pop();
console.log(n.val);
}
};
postorder(bt);