题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://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
if(root == null){
return new int[3][0];
}
List<Integer> list = new ArrayList();
printNodeFirst(root, list);
int[][] result = new int[3][list.size()];
addVal(0, result, list);
printNodeCenter(root, list);
addVal(1, result, list);
printNodeLast(root, list);
addVal(2, result, list);
return result;
}
private void addVal(int line, int[][] result, List<Integer> list){
int i = 0;
for(Integer val : list){
result[line][i] = val;
i++;
}
list.clear();
}
private void printNodeFirst(TreeNode root, List list){
if(root == null){
return;
}
list.add(root.val);
printNodeFirst(root.left, list);
printNodeFirst(root.right, list);
}
private void printNodeCenter(TreeNode root, List list){
if(root == null){
return;
}
printNodeCenter(root.left, list);
list.add(root.val);
printNodeCenter(root.right, list);
}
private void printNodeLast(TreeNode root, List list){
if(root == null){
return;
}
printNodeLast(root.left, list);
printNodeLast(root.right, list);
list.add(root.val);
}
}
#猹的刷题生涯#
/*
* 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
if(root == null){
return new int[3][0];
}
List<Integer> list = new ArrayList();
printNodeFirst(root, list);
int[][] result = new int[3][list.size()];
addVal(0, result, list);
printNodeCenter(root, list);
addVal(1, result, list);
printNodeLast(root, list);
addVal(2, result, list);
return result;
}
private void addVal(int line, int[][] result, List<Integer> list){
int i = 0;
for(Integer val : list){
result[line][i] = val;
i++;
}
list.clear();
}
private void printNodeFirst(TreeNode root, List list){
if(root == null){
return;
}
list.add(root.val);
printNodeFirst(root.left, list);
printNodeFirst(root.right, list);
}
private void printNodeCenter(TreeNode root, List list){
if(root == null){
return;
}
printNodeCenter(root.left, list);
list.add(root.val);
printNodeCenter(root.right, list);
}
private void printNodeLast(TreeNode root, List list){
if(root == null){
return;
}
printNodeLast(root.left, list);
printNodeLast(root.right, list);
list.add(root.val);
}
}
#猹的刷题生涯#