【每日一题】【list转int数组】【Lambda的简化-方法引用】2022年1月15日-NC45 实现二叉树先序,中序和后序遍历
描述
给定一棵二叉树,分别按照二叉树先序,中序和后序打印所有的节点。
数据范围:0 \le n \le 10000≤n≤1000,树上每个节点的val值满足 0 \le val \le 1000≤val≤100
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
样例解释:
答案:Lambda的简化-方法引用,list转int数组
import java.util.*; public class Solution { /** * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ public int[][] threeOrders (TreeNode root) { List<Integer> preList = new ArrayList<>(); List<Integer> inList = new ArrayList<>(); List<Integer> postList = new ArrayList<>(); preOrder(root, preList); inOrder(root, inList); postOrder(root, postList); int[][] res = new int[3][preList.size()]; //转为int数组,需要用mapToInt res[0] = preList.stream().mapToInt(Integer::valueOf).toArray(); res[1] = inList.stream().mapToInt(Integer::valueOf).toArray(); res[2] = postList.stream().mapToInt(Integer::valueOf).toArray(); return res; } public void preOrder(TreeNode root, List<Integer> preList) { if(root == null) return; preList.add(root.val); preOrder(root.left, preList); preOrder(root.right, preList); } public void inOrder(TreeNode root, List<Integer> inList) { if(root == null) return; inOrder(root.left, inList); inList.add(root.val); inOrder(root.right, inList); } public void postOrder(TreeNode root, List<Integer> postList) { if(root == null) return; postOrder(root.left, postList); postOrder(root.right, postList); postList.add(root.val); } }
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/15806159.html