/**
* 简单中序遍历,递归方法
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 37.1 MB, less than 68.57%
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
helper(res, root);
return res;
}
private void helper(List<Integer> res, TreeNode root) {
if (root == null)
return;
helper(res, root.left);
res.add(root.val);
helper(res, root.right);
}
}
/**
* 循环方法
* 对于每一个子树根节点,先一直往左走,用stack保存沿途的节点
* 到null后pop出来将val加入res,然后继续遍历以右子节点为根节点的子树
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 37.1 MB, less than 68.57%
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<>();
Stack<TreeNode> s = new Stack<>();
TreeNode curr = root;
while(curr != null || !s.isEmpty()) {
while (curr != null) {
s.push(curr);
curr = curr.left;
}
curr = s.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}