实现二叉树前序、中序、后序遍历javascript:void(0);
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/questionTerminal/a9fec6c46a684ad5a3abd4e365a9d362
- 递归实现前序、中序、后序遍历,用List进行存储
- Stream流化将List转为int[]
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整型二维数组 */ private List<Integer> preOrder = new LinkedList<>(); private List<Integer> inOrder = new LinkedList<>(); private List<Integer> postOrder = new LinkedList<>(); public int[][] threeOrders (TreeNode root) { // write code here preOrder(root); inOrder(root); postOrder(root); int[] preOrderArray = preOrder.stream().mapToInt(Integer::intValue).toArray(); int[] inOrderArray = inOrder.stream().mapToInt(Integer::intValue).toArray(); int[] postOrderArray = postOrder.stream().mapToInt(Integer::intValue).toArray(); return new int[][]{preOrderArray, inOrderArray, postOrderArray}; } public void preOrder(TreeNode root) { if(root == null) return; preOrder.add(root.val); preOrder(root.left); preOrder(root.right); } public void inOrder(TreeNode root) { if(root == null) return; inOrder(root.left); inOrder.add(root.val); inOrder(root.right); } public void postOrder(TreeNode root) { if(root == null) return; postOrder(root.left); postOrder(root.right); postOrder.add(root.val); } }