题目描述:
分别按照二叉树先序,中序,后序打印所有的节点
输入:
{1,2,3}
返回值
[[1,2,3],[2,1,3],[2,3,1]]
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; private int inIndex = 0; private int postIndex = 0; public int[][] threeOrders (TreeNode root) { // write code here // 前序 int size = getNums(root); int[][] res = new int[3][size]; preOrder(root,res); inOrder(root,res); postOrder(root,res); return res; } public void postOrder(TreeNode root,int[][] res){ if(root == null){ return; } postOrder(root.left,res); postOrder(root.right,res); res[2][postIndex++] = root.val; } public void inOrder(TreeNode root,int[][] res){ if(root == null){ return; } inOrder(root.left,res); res[1][inIndex++] = root.val; inOrder(root.right,res); } public void preOrder(TreeNode root,int[][] res){ if(root == null){ return; } res[0][preIndex++] = root.val; preOrder(root.left,res); preOrder(root.right,res); } public int getNums(TreeNode root){ if (root == null ){ return 0; } /* root TreeNode@7d4991ad root.left TreeNode@28d93b30 root.right TreeNode@1b6d3586 root TreeNode@28d93b30 root.left null root.right null root TreeNode@1b6d3586 root.left null root.right null */ System.out.println("root " + root); System.out.println("root.left " + root.left); System.out.println("root.right " + root.right); return 1 + getNums(root.left) + getNums(root.right); } }