题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
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整型二维数组
* 就是写了三道简单题,二叉树前序中序后序遍历
*/
public int[][] threeOrders (TreeNode root) {
// write code here
preorder(root, list1);
inorder(root, list2);
afterorder(root, list3);
int n = list1.size();
int[][] arr = new int[3][n];
for(int i = 0; i < n; i++){
arr[0][i] = list1.get(i);
arr[1][i] = list2.get(i);
arr[2][i] = list3.get(i);
}
return arr;
}
List<Integer> list1 = new ArrayList<>();
public void preorder(TreeNode root, List<Integer> list){
if(root == null) return;
list1.add(root.val);
preorder(root.left, list);
preorder(root.right, list);
}
List<Integer> list2 = new ArrayList<>();
public void inorder(TreeNode root, List<Integer> list){
if(root == null) return;
inorder(root.left, list);
list2.add(root.val);
inorder(root.right, list);
}
List<Integer> list3 = new ArrayList<>();
public void afterorder(TreeNode root, List<Integer> list){
if(root == null) return;
afterorder(root.left, list);
afterorder(root.right, list);
list3.add(root.val);
}
}