NC45 实现二叉树先序,中序和后序遍历
描述
分别按照二叉树先序,中序和后序打印所有的节点。
示例1
输入:
{1,2,3}
复制
返回值:
[[1,2,3],[2,1,3],[2,3,1]]
复制
import java.util.*;
public class Solution {
public int[][] threeOrders (TreeNode root) {
//调用先序遍历
TreeNode a = root;
List<Integer> preList = new ArrayList<Integer>();
preList = preorderTraversal(a);
int preRes[] = new int[preList.size()];
for(int o = 0; o < preList.size(); o++){
preRes[o] = preList.get(o);
}
//调用中序遍历
TreeNode b = root;
List<Integer> inList = new ArrayList<Integer>();
inList = inorderTraversal(b);
int inRes[] = new int[inList.size()];
for(int p = 0; p < inList.size(); p++){
inRes[p] = inList.get(p);
}
//调用后序遍历
TreeNode c = root;
List<Integer> postList = new ArrayList<Integer>();
postList = postorderTraversal(c);
int postRes[] = new int[postList.size()];
for(int q = 0; q < postList.size(); q++){
postRes[q] = postList.get(q);
}
//整理输出结果
int result[][] = {preRes, inRes, postRes};
return result;
}
//先序遍历(递归)
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) {
return res ;
}
List<Integer> left = preorderTraversal(root.left);
List<Integer> right = preorderTraversal(root.right);
res.add(root.val);
res.addAll(left);
res.addAll(right);
return res;
}
//中序遍历(递归)
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) {
return res ;
}
List<Integer> left = inorderTraversal(root.left);
List<Integer> right = inorderTraversal(root.right);
res.addAll(left);
res.add(root.val);
res.addAll(right);
return res;
}
//后序遍历(递归)
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res ;
}
List<Integer> left = postorderTraversal(root.left);
List<Integer> right = postorderTraversal(root.right);
res.addAll(left);
res.addAll(right);
res.add(root.val);
return res;
}
}