题解 | #实现二叉树先序,中序和后序遍历#

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

http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

java实现,写简单点

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */

    private List<Integer> list = new ArrayList<>();
    public int[][] threeOrders (TreeNode root) {
        // write code here
        int [][] arr = new int[3][];

        for (int i = 0; i < 3; i++) {
            list.clear();
            orders(root,i + 1);
            arr[i] = new int[list.size()];
            for (int j = 0; j < list.size(); j++) {
                arr[i][j] = list.get(j);
            }
        }
        return arr;
    }

    public void orders(TreeNode root,int type) {
        if (root == null) return;
        if (type == 1) 
            list.add(root.val);
            orders(root.left,type);
        if (type == 2) 
            list.add(root.val);
            orders(root.right,type);
        if (type == 3)
            list.add(root.val);
    }
}
全部评论

相关推荐

7月12日投的,咋一点反馈都没有
投递禾赛科技等公司10个岗位
点赞 评论 收藏
分享
07-02 10:39
门头沟学院 Java
Steven267:说点真实的,都要秋招了,还没有实习,早干嘛去了,本来学历就差,现在知道急了,而且你这个简历完全可以写成一页,劣势太大了,建议转测试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务