二叉樹:每個節點最多隻有兩個位元組點
JS中通常用 Object來模擬二叉樹
(val: 1, left: 0, right: 0)
const bt = {
val: 1,
left: {
val: 2,
left: {
val: 4,
left: null,
right: null,
},
right: {
val: 5,
left: null,
right: null,
},
},
right: {
val: 3,
left: {
val: 6,
left: null,
right: null,
},
right: {
val: 7,
left: null,
right: null,
},
},
};
先序遍歷演算法(preorder)「根左右」
1:訪問根節點
2:對根節點的左子樹進行先序遍歷
3:對根節點的右子樹進行先序遍歷
遞迴遍歷
非遞迴(利用棧)
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); } };
preorder(bt);
中序遍歷演算法(inorder): 「左根右」
1:對根節點的左子樹進行中序遍歷
2:訪問根節點
3:對根節點的右了樹進行中序遍歷
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);
後序遍歷演算法(postorder):「左右根」
1:對根節點的左子樹進行後序遍歷
2:對根節點的右子樹進行後序遍歷
3:訪問根節點
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);