{ val: 'a', left: { val: 'b', left: { val: 'c', left: null, right: null }, right: { val: 'd', left: null, right: null } }, right: { val: 'e', left: { val: 'f', left: null, right: null }, right: { val: 'g', left: null, right: null } } }
算法口诀:(根 —> 左 —> 右)
const root = { val: 'a', left: { val: 'b', left: { val: 'c', left: null, right: null }, right: { val: 'd', left: null, right: null } }, right: { val: 'e', left: { val: 'f', left: null, right: null }, right: { val: 'g', left: null, right: null } } }; const preorder = (root) => { if (!root) return; console.log(root.val); preorder(root.left); preorder(root.right); } preorder(root); // 输出:a b c d e f g
算法口诀:(左 —> 根 —> 右)
const root = { val: 'a', left: { val: 'b', left: { val: 'c', left: null, right: null }, right: { val: 'd', left: null, right: null } }, right: { val: 'e', left: { val: 'f', left: null, right: null }, right: { val: 'g', left: null, right: null } } }; const midorder = (root) => { if (!root) return; midorder(root.left); console.log(root.val); midorder(root.right); } midorder(root); // 输出: c b d a f e g
算法口诀:(左 —> 右 —> 根)
const root = { val: 'a', left: { val: 'b', left: { val: 'c', left: null, right: null }, right: { val: 'd', left: null, right: null } }, right: { val: 'e', left: { val: 'f', left: null, right: null }, right: { val: 'g', left: null, right: null } } }; const nextorder = (root) => { if (!root) return; nextorder(root.left); nextorder(root.right); console.log(root.val); } nextorder(root); // 输出: c d b f g e a
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(root);
const midorder = (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; } } midorder(root);
const nextorder = (root) => { if (!root) return; const stack = [root]; const outStack = []; while (stack.length) { const n = stack.pop(); outStack.push(n); if (n.left) stack.push(n.left); if (n.right) stack.push(n.right); } while (outStack.length) { const r = outStack.pop(); console.log(r.val) } } nextorder(root);