实现二叉树先序,中序和后序遍历
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/questionTerminal/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整型二维数组 */ List<Integer> front = new ArrayList<>(); List<Integer> mid = new ArrayList<>(); List<Integer> back = new ArrayList<>(); public int[][] threeOrders (TreeNode root) { // write code here PreorderTraversal(root); InorderTraversal(root); PostorderTraversal(root); int[][] res = { front.stream().mapToInt(Integer::valueOf).toArray(), mid.stream().mapToInt(Integer::valueOf).toArray(), back.stream().mapToInt(Integer::valueOf).toArray() }; return res; } //前序遍历 public void PreorderTraversal(TreeNode root){ if(root == null) return; front.add(root.val); PreorderTraversal(root.left); PreorderTraversal(root.right); } //中序遍历 public void InorderTraversal(TreeNode root){ if(root == null) return; InorderTraversal(root.left); mid.add(root.val); InorderTraversal(root.right); } //后序遍历 public void PostorderTraversal(TreeNode root){ if(root == null) return; PostorderTraversal(root.left); PostorderTraversal(root.right); back.add(root.val); } }