题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
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
ArrayList<ArrayList<Integer>> returnList = new ArrayList<>();
returnList.add(new ArrayList<Integer>());
returnList.add(new ArrayList<Integer>());
returnList.add(new ArrayList<Integer>());
firstOrder(root,returnList.get(0));
middleOrder(root,returnList.get(1));
lastOrder(root,returnList.get(2));
int[][] returnMatrix = new int[3][];
for(int i = 0; i < 3; i++){
returnMatrix[i] = new int[returnList.get(i).size()];
for(int j = 0 ; j < returnList.get(i).size(); j++){
returnMatrix[i][j] = returnList.get(i).get(j);
}
}
return returnMatrix;
}
public void firstOrder(TreeNode root,ArrayList<Integer> scanList){
if(root != null){
scanList.add(root.val);
firstOrder(root.left,scanList);
firstOrder(root.right,scanList);
}
}
public void middleOrder(TreeNode root,ArrayList<Integer> scanList){
if(root != null){
middleOrder(root.left,scanList);
scanList.add(root.val);
middleOrder(root.right,scanList);
}
}
public void lastOrder(TreeNode root,ArrayList<Integer> scanList){
if(root != null){
lastOrder(root.left,scanList);
lastOrder(root.right,scanList);
scanList.add(root.val);
}
}
}