什么是二叉树?

树中每个节点最多只能有两个子节点,在 JavaScript 中一般都是通过 Object 来模拟二叉树。

常用操作

  • 前序遍历
  • 中序遍历
  • 后序遍历

前序遍历

根左右。

口诀:

  1. 访问根节点
  2. 对根节点的左子树进行前序遍历
  3. 对根节点的右子树进行前序遍历

二叉树 - 图1

  1. function preorder(root) {
  2. if (!root) return;
  3. console.log(root.val);
  4. preorder(root.left);
  5. preorder(root.right);
  6. }
  1. function preorder(root) {
  2. if (!root) return;
  3. const stack = [root];
  4. while (stack.length) {
  5. const n = stack.pop();
  6. console.log(n);
  7. if (n.right) stack.push(n.right);
  8. if (n.left) stack.push(n.left);
  9. }
  10. }

中序遍历

左根右。

口诀:

  1. 对根节点的左子树进行中序遍历
  2. 访问根节点
  3. 对根节点的右子树进行中序遍历

二叉树 - 图2

  1. function inorder(root) {
  2. if (!root) return;
  3. inorder(root.left);
  4. console.log(root.val);
  5. inorder(root.right);
  6. }
  1. function inorder(root) {
  2. if (!root) return;
  3. const stack = [root];
  4. while (stack.length) {
  5. const n = stack.pop();
  6. console.log(n);
  7. if (n.right) stack.push(n.right);
  8. if (n.left) stack.push(n.left);
  9. }
  10. }

后序遍历

左右根。

口诀:

  1. 对根节点的左子树进行后序遍历
  2. 对根节点的右子树进行后序遍历
  3. 访问根节点

二叉树 - 图3

  1. function postorder(root) {
  2. if (!root) return;
  3. postorder(root.left);
  4. postorder(root.right);
  5. console.log(root.val);
  6. }
  1. function postorder(root) {
  2. if (!root) return;
  3. const outputStack = [];
  4. const stack = [root];
  5. while (stack.length) {
  6. const n = stack.pop();
  7. outputStack.push(n);
  8. if (n.left) stack.push(n.left);
  9. if (n.right) stack.push(n.right);
  10. }
  11. while (outputStack.length) {
  12. const n = outputStack.pop();
  13. console.log(n.val);
  14. }
  15. }