java 同时进行前中后序遍历
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
import java.util.*;
public class Solution {
ArrayList<Integer> first=new ArrayList<Integer>();
ArrayList<Integer> middle=new ArrayList<Integer>();
ArrayList<Integer> back=new ArrayList<Integer>();
int[][] all=new int[3][];
public int[][] threeOrders (TreeNode root) {
if(root!=null){
// 前序:根永远先输出,先输出的意思就是在找孩子之前
first.add(root.val);
if(root.left!=null){
threeOrders(root.left);
}
// 中序:找完左孩子之后即为根
middle.add(root.val);
if(root.right!=null){
threeOrders(root.right);
}
// 后序:在找完左右孩子之后再轮到自己
back.add(root.val);
}
all[0]=first.stream().mapToInt(Integer::intValue).toArray();
all[1]= middle.stream().mapToInt(Integer::intValue).toArray();
all[2]= back.stream().mapToInt(Integer::intValue).toArray();
return all;
}
}