Java 超级简洁 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
public class Solution { public int[][] threeOrders(TreeNode root) { List<Integer> list = new ArrayList(); dfs(root, list, 1); dfs(root, list, 2); dfs(root, list, 3); int[][] res = new int[3][list.size() / 3]; int index = 0; for (int i = 0; i < res.length; i++) { for (int j = 0; j < res[0].length; j++) { res[i][j] = list.get(index++); } } return res; } //根据状态不同去采用不同的算法 public void dfs(TreeNode node, List<Integer> res, int flag) { if (node == null) return; if (flag == 1) res.add(node.val); dfs(node.left, res, flag); if (flag == 2) res.add(node.val); dfs(node.right, res, flag); if (flag == 3) res.add(node.val); } }