分别按照二叉树先序,中序和后序打印所有的节点。输入{1,2,3}输出[[1,2,3],[2,1,3],[2,3,1]]
解题:
1. 首先题目让返回的是一个二维数组,这样我们首先要确定每个二维数组的个数(getSize())
2. 之后就按照二叉树前中后遍历输出即可
先序遍历:根左右
中序遍历:左根右
后续遍历:左右根
题解
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) {
int[][] res = new int[3][getSize()];
preOrder(root,res);
inOrder(root,res);
postorder(root,res);
return res;
}
//确定每个二位数组个数
public int getSize(TreeNode root){
if(root==null) return 0;
return 1+getSize(root.left)+getSize(root.right);
}
//先序遍历 根左右
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 void inOrder(TreeNode root,int[][] res){
if(root=null) return;
preOrder(root.left,res);
res[1][inIndex++]=root.val;
preOrder(root.right,res);
}
//中序遍历 左根右
public void postOrder(TreeNode root,int[][] res){
if(root=null) return;
preOrder(root.left,res);
preOrder(root.right,res);
res[2][postIndex++]=root.val;
}
}
以上解法还可以简写为如下方式:
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) {
int[][] res = new int[3][getSize()];
order(root,res);
return res;
}
//确定每个二位数组个数
public int getSize(TreeNode root){
if(root==null) return 0;
return 1+getSize(root.left)+getSize(root.right);
}
//遍历
public void Order(TreeNode root,int[][] res){
if(root=null) return;
res[0][preIndex++]=root.val;
order(root.left,res);
res[1][inIndex++]=root.val;
order(root.right,res);
res[2][inIndex++]=root.val;
}
}