leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

94. 二叉树的中序遍历

Open buuing opened this issue 4 years ago • 0 comments

给定一个二叉树的根节点 root ,返回它的 中序 遍历。

示例 1:

image

输入:root = [1,null,2,3]
输出:[1,3,2]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

示例 4:

image

输入:root = [1,2]
输出:[2,1]

示例 5:

image

输入:root = [1,null,2]
输出:[1,2]

提示:

  • 树中节点数目在范围 [0, 100]
  • -100 <= Node.val <= 100

进阶: 递归算法很简单,你可以通过迭代算法完成吗?


来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。




image

  • 中序遍历 - 递归
const inorderTraversal = root => {
  if (!root) return []
  const res = [root.val]
  if (root.left) {
    res.unshift(...inorderTraversal(root.left))
  }
  if (root.right) {
    res.push(...inorderTraversal(root.right))
  }
  return res
}
  • 中序遍历 - 迭代
const inorderTraversal = root => {
  if (!root) return []
  const stack = [root], res = []
  while (stack.length) {
    const curr = stack.pop()
    if (curr.right) {
      if (curr.left && curr.left.val || !curr.left) {
        stack.push(curr.right)
      }
    }
    if (curr.left && curr.left.val) {
      stack.push(curr)
      stack.push(curr.left)
    } else {
      res.push(curr.val)
      curr.val = null
    }
  }
  return res
}

buuing avatar Dec 30 '20 14:12 buuing