题目描述
方法思路
Approach1: recursive
class Solution {
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 36.3 MB, less than 11.58%
List<Integer> res = new LinkedList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null) return res;
inorderTraversal(root.left);
res.add(root.val);
inorderTraversal(root.right);
return res;
}
}
Approach2: iteratively
public class Solution {
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 36.1 MB, less than 66.62%
public List < Integer > inorderTraversal(TreeNode root) {
List < Integer > res = new ArrayList < > ();
Stack < TreeNode > stack = new Stack < > ();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}