第25天--算法(Leetcode 91,101,102)

91.解码方法

public int numDecodings(String s) {
        char s1[] = s.toCharArray();
        int N = s1.length;
        int dp[] = new int[N + 1];
        dp[N] = 1;
        for(int index = N - 1;index >= 0;index --) {
            if(s1[index] == '0') {
                continue;
            }
            int ways = dp[index + 1];
            if(index + 1 >= s1.length) {
                dp[index] = ways;
                continue;
            }
            int num = (s1[index] - '0') * 10 + s1[index + 1] - '0';
            if(num <= 26) {
                ways += dp[index + 2];
            }
            dp[index] = ways;
        }
        return dp[0];
    }
101.对称二叉树
public boolean isSymmetric(TreeNode root) {
        return isMirror(root,root);
    }
    public boolean isMirror(TreeNode t1,TreeNode t2) {
        if(t1 == null && t2 == null) {
            return true;
        }
        if(t1 != null && t2 != null) {
            return t1.val == t2.val && isMirror(t1.left,t2.right) && isMirror(t1.right,t2.left);
        }
        return false;
    }
102.二叉树的层序遍历
public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if(root == null) {
            return ans;
        }
        LinkedList<TreeNode> ls = new LinkedList<>();
        ls.addFirst(root);
        int size = 0;
        while(!ls.isEmpty()) {
            size = ls.size();
            List<Integer> cur = new ArrayList<>();
            for(int i = 0;i < size;i ++) {
                TreeNode t = ls.pollLast();
                if(t.left != null) {
                    ls.addFirst(t.left);
                }
                if(t.right != null) {
                    ls.addFirst(t.right);
                }
                cur.add(t.val);
            }
            ans.add(cur);
        }
        return ans;
    }
posted @ 2022-01-24 15:26  现在开始努力  阅读(31)  评论(0)    收藏  举报