LeetCode刷题系列-94. 二叉树的中序遍历

题目

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

输入: [1,null,2,3]
   1
    \
     2
    /
   3
输出: [1,3,2]

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

解法一:递归

解题思路

树的前序、中序和后序遍历都可以通过递归解决。这里将大问题拆分成小问题,写递归式子:

  • 假如第n个节点的中序遍历结果为f(n),那么它就由当前节点左子树的中序遍历结果加上当前节点的值 以及当前节点右子树的中序遍历结果,即f(n) = f(n.left).concat(n.val, f(n.right))
  • 边界条件 f(null) = []

代码实现

// 省事版
const inorderTraversal = function (root) {
    
    
  if (root === null) return [];
  
  return inorderTraversal(root.left).concat(
    [root.val],
    inorderTraversal(root.right)
  );
};

// 优化版
const inorderTraversal = function (root) {
    
    
  const core = (node, res) => {
    
    
    if (node !== null) {
    
    
      core(node.left, res);
      res.push(node.val);
      core(node.right, res);
    }
  };
  let result = [];
  core(root, result);
  return result;
};

复杂度分析

时间复杂度: O ( n ) O(n) O(n)。递归函数: T ( n ) = 2 ⋅ T ( n / 2 ) + 1 T(n) = 2 \cdot T(n/2)+1 T(n)=2T(n/2)+1
空间复杂度:最坏情况下需要空间 O ( n ) O(n) O(n),平均情况为 O ( log ⁡ n ) O(\log n) O(logn)

解法二:迭代

解题思路

利用栈模拟递归,核心是保护现场以及还原现场

代码实现

const inorderTraversal = function (root) {
    
    
  if (root === null) return [];
  const stack = [root];
  const result = [];
  while (stack.length > 0) {
    
    
    let node = stack.pop();
    if (node.left !== null) {
    
    
      let left = node.left;
      node.left = null;
      stack.push(node);
      stack.push(left);
      continue;
    }
    result.push(node.val);
    if (node.right !== null) {
    
    
      stack.push(node.right);
    }
  }
  return result;
};

复杂度分析

时间复杂度: O ( n ) O(n) O(n),空间复杂度: O ( n ) O(n) O(n)

猜你喜欢

转载自blog.csdn.net/sinat_36521655/article/details/107374254