94. 二叉树的中序遍历 + 递归实现 + 非递归实现
94. 二叉树的中序遍历
LeetCode_94
题目描述
解法一:递归解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
inTravels(root);
return list;
}
public void inTravels(TreeNode now){
if(now == null)
return;
inTravels(now.left);
list.add(now.val);
inTravels(now.right);
}
}
非递归实现
- 我们可以使用栈来模拟递归的过程
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> sta = new Stack<>();
while(root != null || !sta.isEmpty()){
while(root != null){
sta.push(root);
root = root.left;
}
root = sta.pop();
list.add(root.val);
root = root.right;
}
return list;
}
}
复杂度分析
两种方法的复杂度都相同
- 时间复杂度:O(n),其中 n 为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次。
- 空间复杂度:O(n)。空间复杂度取决于栈深度,而栈深度在二叉树为一条链的情况下会达到 O(n) 的级别。
Either Excellent or Rusty