实现二叉树的先序,中序,后序
题目描述
分别按照二叉树先序,中序和后序打印所有的节点。
代码
import java.util.*;
/*
* 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整型二维数组
*/
private int preIndex = 0, inIndex = 0, postIndex = 0;
public int[][] threeOrders (TreeNode root) {
// write code here
int n = count(root);
int[][] res = new int[3][n];
orders(res, root);
return res;
}
public int count(TreeNode root){
if(root==null){
return 0;
}
return 1+count(root.left)+count(root.right);
}
public void orders(int[][] res, TreeNode root){
if(root==null){
return ;
}
res[0][preIndex++] = root.val;
orders(res,root.left);
res[1][inIndex++] = root.val;
orders(res,root.right);
res[2][postIndex++] = root.val;
}
}