leetcode題解-606. Construct String from Binary Tree && 657. Judge Route Circle

這兩道題目都相對比較簡單,所以就一起總結一下,先來看第一道:
606,construct string from binary tree,題目:

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

Example 1:
Input: Binary tree: [1,2,3,4]
       1
     /   \
    2     3
   /    
  4     

Output: "1(2(4))(3)"

Explanation: Originallay it needs to be "1(2(4)())(3()())", 
but you need to omit all the unnecessary empty parenthesis pairs. 
And it will be "1(2(4))(3)".
Example 2:
Input: Binary tree: [1,2,3,null,4]
       1
     /   \
    2     3
     \  
      4 

Output: "1(2()(4))(3)"

Explanation: Almost the same as the first example, 
except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output

本題是從二叉樹生成字符串,要求使用括號來表示父子關係,並且如果爲葉子結點則兩個括號都不要,如果左孩子爲空右孩子不空則左孩子用括號表示,反之有孩子爲空時,則不用任何記號,直接爲空即可。這種題目一看就會想到使用遞歸的方式來遍歷二叉樹,所以寫出下面的代碼,一遍過而且可以擊敗90%的用戶:

    public String tree2str(TreeNode t) {
        StringBuilder res = new StringBuilder();
        res = dfs(t, res);
        return res.toString();
    }

    public StringBuilder dfs(TreeNode t, StringBuilder res){
         StringBuilder tmp = res;
         //如果當前節點爲空則直接返回結果即可,否則將當前節點的值添加到結果字符串中
         if(t == null)
             return res;
         else
             tmp.append(t.val);

        //如果左孩子不爲空,則添加到字符串並繼續遞歸其左孩子,否則的話,如果右孩子不爲空,則直接添加()即可
         if(t.left != null){
             tmp.append('(');
             tmp = dfs(t.left, tmp);
             tmp.append(')');
         }else if(t.right != null)
             tmp.append("()");

        //如果右孩子不爲空,則遍歷其右孩子節點,並添加相關信息
         if(t.right != null){
             tmp.append('(');
             tmp = dfs(t.right, tmp);
             tmp.append(')');
         }
         //說明左右孩子均爲空,已遍歷完成,返回字符串即可
         return tmp;
    }

然後又去看了別人的解決方案,發現了另外一種解決方案,但是效率上可能會有所降低,如下所示:

    public static String tree2str2(TreeNode t) {
        if(t == null) return "";
        return dfs1(t).toString();
    }

    public static StringBuilder dfs1(TreeNode t) {
        if(t == null) return null;

        StringBuilder sb = new StringBuilder();
        sb.append(t.val);

        //先定義兩個字符串來保存左右孩子的表示,並一直深度遍歷下去
        StringBuilder left = dfs1(t.left);
        StringBuilder right = dfs1(t.right);

        //根據題目需求,設置判斷條件添加括號
        if(right == null && left == null) return sb;
        sb.append("(").append(left == null ? "" : left).append(")");
        if(right != null) sb.append("(").append(right).append(")");
        return sb;
    }

657。judge route circle。題目:

Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle,

which means it moves back to the original place.

The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R

(Right), L (Left), U (Up) and D (down). The output should be true or false representing whether the robot makes a circle.

Example 1:
Input: "UD"
Output: true
Example 2:
Input: "LL"
Output: false

本題很簡單,直接遍歷字符串統計其UDRL四個字符出現的次數,然後看是否兩兩相等即可。代碼如下所示,記得轉化成char型數組在遍歷哦:

    public boolean judgeCircle1(String moves){
        char [] move = moves.toCharArray();
        int up=0, right=0;
        for(char c : move){
            if(c == 'U')
                up ++;
            else if(c == 'D')
                up --;
            else if(c == 'R')
                right ++;
            else
                right --;

        }
        return up == 0 && right ==0;
    }

還有一種騷操作,只需要兩行代碼,但是效率比較低,只能擊敗4%的用戶:

    public boolean judgeCircle2(String moves) {
        moves=" " + moves + " ";
        return moves.split("L").length==moves.split("R").length && moves.split("U").length == moves.split("D").length;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章