662. Maximum Width of Binary Tre

2017-08-21  本文已影响156人  DrunkPian0

Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.
Example 1:
Input:

       1
     /   \
    3     2
   / \     \  
  5   3     9 

Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

求二叉树最大宽度。这题挺好的,我没做出来。我想的BFS是用leetcode那样的序列化一颗二叉树的方法,把null也加进去最后找最长的一个itemList,但我没看到这样的答案,大家都是利用左子树节点是根节点的2倍这个规律做的。

BFS

    public int widthOfBinaryTree(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<Integer> indice = new LinkedList<>();
        queue.add(root);
        indice.add(0);
        int max = 1;
        int leftMost = 0, rightMost = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                int index = indice.poll();
                if (i == 0) leftMost = index;
                if (i == size - 1) rightMost = index;
                if (node.left != null) {
                    queue.add(node.left);
                    indice.add(index * 2);
                }
                if (node.right != null) {
                    queue.add(node.right);
                    indice.add(index * 2 + 1);
                }
            }
            max = Math.max(max, rightMost - leftMost + 1);
        }
        return max;
    }

DFS

    public int widthOfBinaryTree(TreeNode root) {
        List<Integer> lefts = new ArrayList<Integer>(); // left most nodes at each level;
        int[] res = new int[1]; // max width
        dfs(root, 1, 0, lefts, res);
        return res[0];
    }
    private void dfs(TreeNode node, int id, int depth, List<Integer> lefts, int[] res) {
        if (node == null) return;
        if (depth >= lefts.size()) lefts.add(id);   // add left most node
        res[0] = Integer.max(res[0], id + 1 - lefts.get(depth));
        dfs(node.left,  id * 2,     depth + 1, lefts, res);
        dfs(node.right, id * 2 + 1, depth + 1, lefts, res);
    }
上一篇 下一篇

猜你喜欢

热点阅读