题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
public int[][] threeOrders (TreeNode root) {
// write code here
List<Integer> listA=new ArrayList<>();
List<Integer> listB=new ArrayList<>();
List<Integer> listC=new ArrayList<>();
//先序遍历
prePrint(root,listA);
//中序遍历
MiddlePrint(root,listB);
//后序遍历
AfterPrint(root,listC);
int[][] arr =new int[3][listA.size()];
for(int i=0;i<listA.size();i++){
arr[0][i]=listA.get(i);
arr[1][i]=listB.get(i);
arr[2][i]=listC.get(i);
}
return arr;
}
//先序遍历
public void prePrint(TreeNode root,List<Integer> list){
if(root==null){
return ;
}
list.add(root.val);
prePrint(root.left,list);
prePrint(root.right,list);
}
//中序遍历
public void MiddlePrint(TreeNode root,List<Integer> list){
if(root==null){
return ;
}
MiddlePrint(root.left,list);
list.add(root.val);
MiddlePrint(root.right,list);
}
//后序遍历
public void AfterPrint(TreeNode root,List<Integer> list){
if(root==null){
return ;
}
AfterPrint(root.left,list);
AfterPrint(root.right,list);
list.add(root.val);
}
}
