一、题目
力扣原题:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
前序遍历:https://blog.csdn.net/sinat_34596644/article/details/106130854
后序遍历:https://blog.csdn.net/sinat_34596644/article/details/106131335
二、递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private List<Integer> result = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (null == root) {
return result;
}
// 递归左子树
if (null != root.left) {
inorderTraversal(root.left);
}
// 添加到结果集
result.add(root.val);
// 递归右子树
if (null != root.right) {
inorderTraversal(root.right);
}
return result;
}
}
- 时间复杂度:O(n)
- 空间复杂度:
- 最优:O(log(n))。二叉树的深度最小时
- 最差:O(n)。二叉树退化为链表时
- 平均:O(log(n))
三、迭代
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
if (null == root) {
return new ArrayList<>();
}
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (!stack.isEmpty() || null != cur) {
// 找到最左节点
while (null != cur) {
stack.push(cur);
cur = cur.left;
}
// 添加到结果集
cur = stack.pop();
result.add(cur.val);
// 指向右节点
cur = cur.right;
}
return result;
}
}
- 基本思路:根据中序遍历的定义(左根右),先递归找到最左节点,而后回溯,最后访问右节点,并按此思路逐层回溯。
- 时间复杂度:O(n)
- 空间复杂度:O(n)