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

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

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);
    }
}
全部评论

相关推荐

notbeentak...:就抓,嗯抓,开不开匿名都要抓,一点坏事不让说,就对公司顶礼膜拜佩服的五体投地就对了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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