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]
递归:
import java.util.ArrayList;
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> ret=new ArrayList<>();
if(root!=null){
ret.addAll(inorderTraversal(root.left));
ret.add(root.val);
ret.addAll(inorderTraversal(root.right));
}
return ret;
}
}
迭代:
import java.util.ArrayList;
import java.util.Stack;
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> ret=new ArrayList<Integer>();
if(root==null){
return ret;
}
Stack<TreeNode> s=new Stack<TreeNode>();
while(root!=null||!s.isEmpty()){
while(root!=null){
s.push(root);
root=root.left;
}
if(!s.isEmpty()){
root=s.pop();
ret.add(root.val);
root=root.right;
}
}
return ret;
}
}