Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3 Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
题意:
二叉树中序遍历
Solution1: Recursion
code
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
storeInorder(root, list);
return list;
}
public void storeInorder(TreeNode node, List<Integer> list) {
if(node == null) return;
storeInorder(node.left, list);
list.add(node.val);
storeInorder(node.right, list);
}
}
Solution2: Iteration
code
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
//left -- root -- right
ArrayList<Integer> result = new ArrayList<>();
Stack<TreeNode> s = new Stack<>();
TreeNode p = root; while(!s.isEmpty() || p!=null){
if(p!=null){
s.push(p);
p = p.left;
}else{
p =s.pop();
result.add(p.val);
p = p.right;
}
}
return result;
}
}