LeetCode 662. Maximum Width of Binary Tree?

树的width的定义是:
每一层的最左和最右之间的额所有Node的数量(包括null node)

idea:
我们给每一层的节点赋值 比如说root位置为0 那么第一层就分别是-1 和 1,如果他们也同样分别往左或者往右扩的时候变为-2和2
我们只需要层次遍历的时候对最左和最右的节点进行更新就行(但是仔细想一下 这实际上是不行的 我们必须要对所有的节点进行位置的维护 因为我们不知道下一层的边界是属于上一层的哪两个父节点的 而这个边界的位置又取决于这两个父节点的位置)
基于这个想法 我用以下代码实现 但是效果很差。

class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int max = 1;
        List<List<Integer>> list = new ArrayList<>();
        width(root, max, 0, list, 0);
        return max;
    }
    
    private void width(TreeNode root, int max, int position, List<List<Integer>> list, int level) { //基于level order traverse代码
        if (root == null) return;
        if (list.size() <= level) {
            list.add(new ArrayList<>());
            if (list.size() > 1) { //in order to 
                int size = list.get(list.size() - 1).size();
            if (max < list.get(list.size() - 1).get(size - 1) - list.get(list.size() - 1).get(0)) {
                max = list.get(list.size() - 1).get(size - 1) - list.get(list.size() - 1).get(0);
            }
            }
        }
        list.get(level).add(position);
        width(root.left, max, position - 1, list, level + 1);
        width(root.right, max, position + 1, list, level + 1);
    } 
}

and the right solution should be(but i don’t understand how it works):

class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        List<Integer> start = new ArrayList<>();
        List<Integer> end = new ArrayList<>();
        return dfs(root, 0, 1, start, end); //dfs will return the max width of this root tree
    }
    
    private int dfs(TreeNode root, int level, int order, List<Integer> start, List<Integer> end) {
        if (root == null) return 0;
        if (start.size() == level) { //don;t understand why, if the size of start is the same as level, means we are moving to next level? so start need to mark this point as starting point of next level
            start.add(order);
            end.add(order);
        } else {
            end.set(level, order); //end will keep update the last element's index
        }
        int width = end.get(level) - start.get(level) + 1;
        int left = dfs(root.left, level + 1, 2 * order, start, end);
        int right = dfs(root.right, level + 1, 2 * order + 1, start, end);
        return Math.max(width, Math.max(left, right));
    }
}
posted @ 2020-11-18 01:20  EvanMeetTheWorld  阅读(16)  评论(0)    收藏  举报