Stay button --- 2020.3.10

543. Binary Tree diameter

class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
            //遍历每一个节点,求出此节点作为根的树的深度,那么,左子树深度加右子树深度的最大值即是答案
            setDepth(root);
            return max;
    }

    public int setDepth(TreeNode root) {
        if (root != null) {
            int right = setDepth(root.right);
            int left = setDepth(root.left);
            if (right + left > max)
                max = right + left;
            return Math.max(right, left) + 1;
        }
        return 0;
    }
}

654. The largest binary tree

//递归+分治
class Solution {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return construct(nums, 0, nums.length);
    }
    public TreeNode construct(int[] nums, int l, int r) {
        if (l == r)
            return null;
        int max_i = max(nums, l, r);
        TreeNode root = new TreeNode(nums[max_i]);
        root.left = construct(nums, l, max_i);
        root.right = construct(nums, max_i + 1, r);
        return root;
    }
    public int max(int[] nums, int l, int r) {
        int max_i = l;
        for (int i = l; i < r; i++) {
            if (nums[max_i] < nums[i])
                max_i = i;
        }
        return max_i;
    }
}

1221. segmentation balance string

//计数法
class Solution {
    public int balancedStringSplit(String s) {
        int num = 0;
        int n = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i)=='R')
                n++;
            if (s.charAt(i) == 'L')
                n--;
            if (n == 0)
                num++;
        }
        return num;
    }
}
//数组模拟栈
public int balancedStringSplit(String s) {

    int count = 0;
    int[] container = new int[s.length()];
    int size = 0;

    for (char c : s.toCharArray()) {
        if (size == 0 || c == container[size-1]) 
            container[size++] = c;              //放入容器
        else if (c != container[size-1]){
            size--;                             //匹配到了互异字母
            if (size == 0)
                count++;
        }
    }
    return count;
}

The more you know, the more you do not know.
Proper way without surgery, patients can still seek, there is no way to surgery, ending surgery.
If you have other questions, welcome message, we can discuss, learn together and progress together

He published 193 original articles · won praise 116 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40722827/article/details/104783171
Recommended