Skip to content

二叉树的中序遍历

javascript
let root = {
  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,
    },
  },
};
var inorderTraversal = function (root) {
  if (!root) return [];
  let res = [];
  let stack = [];
  let p = root;
  while (stack.length || p) {
    while (p) {
      stack.push(p);
      p = p.left;
    }
    let node = stack.pop();
    res.push(node.val);
    if (node.right) {
      p = node.right;
    }
  }
  return res;
};
console.log(inorderTraversal(root));