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

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

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

思路:

先,中,后遍历存到一个集合里,然后遍历集合填充数组,数组列长度需在第一次先序遍历后计算,也可以最后集合长度除以3获得;
public class Solution {
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */
    public int[][] threeOrders (TreeNode root) {
        // write code here
        // 先序遍历
        ArrayList<Integer> list = new ArrayList();
        preorder(root, list);
        int m = list.size();
        int[][] arr = new int[3][m];
        inorder(root, list);
        postorder(root, list);
        int k = 0;
        for(int i = 0; i<3; i++){
            for(int j = 0; j<m; j++){
                arr[i][j] = list.get(k++);
            }
        }
        return arr;
    }
    private void preorder(TreeNode root, ArrayList<Integer> list){
        if( root == null){
            return ;
        }
        list.add(root.val);
        preorder(root.left, list);
        preorder(root.right,list);
    }
    private void inorder(TreeNode root, ArrayList<Integer> list){
        if(root == null){
            return ;
        }
         inorder(root.left, list);
         list.add(root.val);
         inorder(root.right, list);
    }
    private void postorder(TreeNode root, ArrayList<Integer> list){
        if(root == null){
            return ;
        }
        postorder(root.left, list);
        postorder(root.right, list);
        list.add(root.val);
    }
}
全部评论

相关推荐

2024-12-05 17:06
已编辑
运营
在拧螺丝的西红柿很热情:基本信息放最上面,看你写的都是一些运营的履历,找运营工作要明确需要会什么内容,去网上查一查,然后上B站学一学,写上去,工作履历最好数据化,比如播放量达到1万➕,用户复购率达到多少等等就数据很重要
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务