题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
// 最简单的递归遍历二叉树算法,水平有限,只能减少空间复杂度,且注意不要犯低级错误 import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ public int[][] threeOrders (TreeNode root) { // write code here,简单的递归算法 List<Integer> preli = new ArrayList<>(); pre(root,preli); List<Integer> inli = new ArrayList<>(); inorder(root,inli); List<Integer> postli = new ArrayList<>(); post(root,postli); //以上操作修改了各自容器遍历顺序 int[][] arr = new int[3][inli.size()];//三组元素,每组若干个元素 for(int i=0;i<preli.size();i++){ arr[0][i] = preli.get(i); } for(int i=0;i<inli.size();i++){ arr[1][i] = inli.get(i); } for(int i=0;i<postli.size();i++){ arr[2][i] = postli.get(i); } //完成元素组的赋值 return arr; } void pre(TreeNode cur , List<Integer> list){ if(cur == null){ return;//如果根结点伪空就结束函数 } list.add(cur.val); pre(cur.left,list); pre(cur.right,list); } void inorder(TreeNode cur , List<Integer> list){ if(cur == null){ return; } inorder(cur.left,list); list.add(cur.val); inorder(cur.right,list); } void post(TreeNode cur , List<Integer> list){ if(cur == null){ return; } post(cur.left,list); post(cur.right,list); list.add(cur.val); } }