
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
/**
* 方法1: 递归
* 时间复杂度:O(n) 空间复杂度:O(n)
*/
/*
List<Integer> res = new ArrayList<>();
dfs(root,res);
return res;
*/
/**
* 方法2:非递归
* 时间复杂度:O(n) 空间复杂度:O(n)
*/
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
res.add(root.val);
root = root.right;
}
return res;
}
private void dfs(TreeNode root, List<Integer> res) {
if (root == null) return;
dfs(root.left, res); // 左
res.add(root.val); // 根
dfs(root.right, res); // 右
}
}