只遍历一遍,贼简单

实现二叉树先序,中序和后序遍历

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<int[]> res;
    public int[][] threeOrders (TreeNode root) {
        // write code here
        res = new ArrayList();
        List<Integer> list1 = new ArrayList(), list2 = new ArrayList(), list3 = new ArrayList();
        dfs(root, list1, list2, list3);
        int[] s1 = list1.stream().mapToInt(Integer::valueOf).toArray();
        res.add(s1);
        res.add(list2.stream().mapToInt(Integer::valueOf).toArray());
        res.add(list3.stream().mapToInt(Integer::valueOf).toArray());
        return res.toArray(new int[res.size()][]);
    }
    private void dfs(TreeNode root, List list1, List list2, List list3) {
        if (root == null) {
            return;
        }
        list1.add(root.val);
        dfs(root.left, list1, list2, list3);
        list2.add(root.val);
        dfs(root.right, list1, list2, list3);
        list3.add(root.val);
    }
}
全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务