前序遍历
public void preOrder(TreeNode root,List<Integer> ret){
if(root==null){
return ;
}
ret.add(root.val);
preOrder(root.left,ret);
preOrder(root.right,ret);
}
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
preOrder(root,ret); //第二个参数类型是List<Integer>
return ret;
}
中序遍历
public void inOrder(TreeNode root,List<Integer> ret){ //返回值是void
if(root==null){
return ;
}
inOrder(root.left,ret);
ret.add(root.val); //.val !!!!
inOrder(root.right,ret);
}
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret=new ArrayList<>();
inOrder(root,ret);
return ret;
}
后序遍历
public void postOrder(TreeNode root,List<Integer> ret){ //返回值是void
if(root==null){
return ;
}
postOrder(root.left,ret);
postOrder(root.right,ret);
ret.add(root.val); //.val !!!!
}
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ret=new ArrayList<>();
postOrder(root,ret);
return ret;
}