题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
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 //集合分别保存三种遍历结果 ArrayList<Integer> list1=new ArrayList<>(); ArrayList<Integer> list2=new ArrayList<>(); ArrayList<Integer> list3=new ArrayList<>(); //前中后遍历 pre(root,list1); mid(root,list2); post(root,list3); //数组进行保存 int arr[][]=new int[3][list1.size()]; //将集合元素添加到数组 for(int i=0;i<list1.size();i++){ arr[0][i]=list1.get(i); arr[1][i]=list2.get(i); arr[2][i]=list3.get(i); } return arr; } //前序 public void pre(TreeNode root,ArrayList<Integer> list){ if(root==null){ return; } list.add(root.val); pre(root.left,list); pre(root.right,list); } //中序 public void mid(TreeNode root,ArrayList<Integer> list){ if(root==null){ return; } mid(root.left,list); list.add(root.val); mid(root.right,list); } //后序 public void post(TreeNode root,ArrayList<Integer> list){ if(root==null){ return; } post(root.left,list); post(root.right,list); list.add(root.val); } }