🥈Medium

给定一个二叉树,返回它的中序遍历。
示例:

  1. 输入: [1,null,2,3]
  2. 1
  3. \
  4. 2
  5. /
  6. 3
  7. 输出: [1,3,2]

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

题解

递归

使用递归算法,应该很简单,竟然还写不出来!!!太垃圾了吧😧
垃圾代码:

Python

错的!
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. def inorderTraversal(self, root: TreeNode) -> List[int]:
  9. ans=[]
  10. if not root:
  11. return ans
  12. if root.left:
  13. self.inorderTraversal(root.left)
  14. ans.append(root.val)
  15. if root.right:
  16. self.inorderTraversal(root.right)
  17. return ans

其实思路没什么问题,但添加root.val时并没有递归!

正确的!
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. def inorderTraversal(self, root: TreeNode) -> List[int]:
  9. ans=[]
  10. def inorder(node):
  11. if not node:
  12. return
  13. inorder(node.left)
  14. ans.append(node.val)
  15. inorder(node.right)
  16. inorder(root)
  17. return ans

JavaScript

  1. var inorderTraversal = function(root) {
  2. const res = [];
  3. const inorder = (root) => {
  4. if (!root) {
  5. return;
  6. }
  7. inorder(root.left);
  8. res.push(root.val);
  9. inorder(root.right);
  10. }
  11. inorder(root);
  12. return res;
  13. };

复杂度分析

  • 时间复杂度:🥈94. 二叉树的中序遍历🌱 - 图1,其中 n 为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。
  • 空间复杂度:🥈94. 二叉树的中序遍历🌱 - 图2。空间复杂度取决于递归的栈深度,而栈深度在二叉树为一条链的情况下会达到 🥈94. 二叉树的中序遍历🌱 - 图3 的级别。

迭代

上面递归的操作也可以用栈来完成。两种方式等价的,只不过是迭代把递归中隐式维护的栈显式模拟出来。如下图所示:
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png
image.png

动图如下
🥈94. 二叉树的中序遍历🌱 - 图18
整体来说还是看节点是否有左子树,如果有就往下走,直到叶子节点,然后再返回中间结点和右子树。

Python

JavaScript

  1. var inorderTraversal = function(root) {
  2. const res = [];
  3. const stk = [];
  4. while (root || stk.length) {
  5. // 把root节点的左子树全部加入
  6. while (root) {
  7. stk.push(root);
  8. root = root.left;
  9. }
  10. root = stk.pop();
  11. res.push(root.val);
  12. root = root.right;
  13. }
  14. return res;
  15. };