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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章