ARTS打卡第十四周

Algorithm: Leetcode 94. Binary Tree Inorder Traversal

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
   1
    \
     2
    /
   3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?

一、遞歸寫法:

    public List<Integer> recursive(TreeNode root) {
        if(root == null) {
            return Collections.emptyList();
        }
        List<Integer> result = new ArrayList<>();
        result.addAll(recursive(root.left));
        result.add(root.val);
        result.addAll(recursive(root.right));
        return result;
    }

分析:時間複雜度O(n),空間複雜度O(n)

二、迭代寫法:

public List<Integer> iterate(TreeNode root) {
        if(root == null) {
            return Collections.emptyList();
        }
        LinkedList<TreeNode> stack = new LinkedList<>();
        List<Integer> result = new ArrayList<>();

        stack.addLast(root);
        while(!stack.isEmpty()) {
            TreeNode node = stack.getLast();
            if(node.left == null) {
                node = stack.removeLast();
                result.add(node.val);
                if (node.right != null) {
                    stack.addLast(node.right);
                }
            } else {
                stack.addLast(node.left);
                node.left = null;
            }
        }
        return result;
    }

分析:時間複雜度O(n),空間複雜度O(n)

Review:

Tip: 使用Jersey上傳下載文件,文件名中文亂碼的解決辦法

在上傳文件的接口中,使用FormDataContentDisposition獲取到的文件名是亂碼,因爲Jersey中默認使用ISO_8859_1對文件名解碼成字符串,此時這個字符串如果包含中文,看到的就是亂碼,需要調用String的getBytes方法重新將其編碼成ISO_8859_1的字節數組,然後在用String的構造方法將其解碼成UTF_8的字符串。

    /**
     * 上傳報竣截圖.
     */
    @POST
    @Path("/file/upload")
    @Produces({MediaType.APPLICATION_JSON})
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public Response uploadNotifyComplementAttachment(@Context SecurityContext sc, 
                                                     @FormDataParam("file") InputStream inputStream,
                                                     @FormDataParam("file") FormDataContentDisposition fileDetail) {
        
            String fileName = new String(fileDetail.getFileName().getBytes(Charsets.ISO_8859_1), Charsets.UTF_8);
           // do something
            return ResponseUtil.creationSucceed();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章