构建二叉树数据
binaryTree.js
const bt = {
val: 1,
left: {
val: 2,
left: {
val: 3,
left: null,
right: null
},
right: {
val: 4,
left: null,
right: null
}
},
right: {
val: 5,
left: {
val: 6,
left: null,
right: null
},
right: {
val: 7,
left: null,
right: null
}
}
}
module.exports = bt;
通过node模块语法导出。
递归版
前序遍历
前序遍历的顺序是先遍历根节点->左节点->右节点 ( 根 左 右 )的形式
const bt = require('./binaryTree.js')
const preorder = (root) => {
if(!root) return;
console.log(root.val) //1 2 3 4 5 6 7
preorder(root.left)
preorder(root.right)
}
preorder(bt);
中序遍历
const bt = require('./binaryTrees.js')
const inorder = (root) => {
if (!root) {return; }
inorder(root.left)
console.log(root.val) //3 2 4 1 6 5 7
inorder(root.right)
}
inorder(bt)
后序遍历
const bt = require('./binaryTrees.js')
const postorder = (root) => {
if (!root) {return; }
postorder(root.left)
postorder(root.right)
console.log(root.val) //3 4 2 6 7 5 1
}
postorder(bt)
非递归版
非递归版需要使用到栈结构,利用栈模拟递归时的堆栈调用顺序
前序遍历
const preorder = (root) => {
if (!root) {return; }
const stack = [root];
while(stack.length>0){
const n = stack.pop()
console.log(n.val)
if (n.right) {stack.push(n.right)}
if (n.left) {stack.push(n.left)}
}
}
preorder(bt)
中序遍历
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
}
}
inorder(bt)
后续遍历
const postorder = (root) => {
if (!root) {return; }
const stack = [root];
const outputStack = [];
while (stack.length > 0) {
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)