二叉树的遍历有三种:
(1)先(根)序遍历(根左右)
(2)中(根)序遍历(左根右)
(3)后(根)序遍历(左右根)
举个例子:
先(根)序遍历(根左右):A B D H E I C F J K G
中(根)序遍历(左根右) : D H B E I A J F K C G
后(根)序遍历(左右根) : H D I E B J K F G C A
下面给出一道题:
题目描述
分别按照二叉树先序,中序和后序打印所有的节点。
输入
{1,2,3}
返回值
[[1,2,3],[2,1,3],[2,3,1]]
先用递归去完成三种遍历
/**
* 先序遍历
*/
public void preorder(TreeNode root, List<Integer> list) {
if (root != null) {
list.add(root.val);
preorder(root.left, list);
preorder(root.right, list);
}
}
/**
* 中序遍历
*/
public void inorder(TreeNode root, List<Integer> list) {
if (root != null) {
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
}
}
/**
* 后序遍历
*/
public int[] postorder(TreeNode root, List<Integer> list) {
if (root != null) {
preorder(root.left, list);
preorder(root.right, list);
list.add(root.val);
}
}
但是需要转换一下二维数组,由于博主知识有限用的笨逼方法去转换的,仅仅给大家做个参考
完整题解
/**
* @Description:
* @ClassName algorithm
* @Author: 王瑞文
* @Date: 2021/1/10 21:17
*/
public class Test {
public int[][] threeOrders (TreeNode root) {
// write code here
int[][] result = new int[3][];
List<Integer> f1 = new ArrayList<>();
f1(root, f1);
Integer[] t1 = new Integer[f1.size()];
f1.toArray(t1);
result[0] = new int[t1.length];
for(int jj = 0; jj < t1.length; jj++) {
result[0][jj] = t1[jj];
}
List<Integer> f2 = new ArrayList<>();
f2(root, f2);
Integer[] t2 = new Integer[f2.size()];
f2.toArray(t2);
result[1] = new int[t2.length];
for(int jj = 0; jj < t2.length; jj++) {
result[1][jj] = t2[jj];
}
List<Integer> f3 = new ArrayList<>();
f3(root, f3);
Integer[] t3 = new Integer[f3.size()];
f3.toArray(t3);
result[2] = new int[t3.length];
for(int jj = 0; jj < t3.length; jj++) {
result[2][jj] = t3[jj];
}
return result;
}
private void f1(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
list.add(root.val);
f1(root.left, list);
f1(root.right, list);
}
private void f2(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
f2(root.left, list);
list.add(root.val);
f2(root.right, list);
}
private void f3(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
f3(root.left, list);
f3(root.right, list);
list.add(root.val);
}
}