Search in sources :

Example 66 with TreeNode

use of com.pkumar7.TreeNode in project interview by dqnn.

the class _1161MaximumLevelSumOfABinaryTree method maxLevelSum.

/*
1161. Maximum Level Sum of a Binary Tree
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.

Return the smallest level X such that the sum of all the values of nodes at level X is maximal.
*/
// thinking process: O(n)/O(n)
// level browse, typical question
public int maxLevelSum(TreeNode root) {
    if (root == null)
        return 0;
    Queue<TreeNode> q = new LinkedList<>();
    q.offer(root);
    int max = root.val;
    int maxLevel = 0, cur = 0;
    while (!q.isEmpty()) {
        int size = q.size();
        int sum = 0;
        cur++;
        while (size-- > 0) {
            TreeNode node = q.poll();
            sum += node.val;
            if (node.left != null)
                q.offer(node.left);
            if (node.right != null)
                q.offer(node.right);
        }
        if (sum > max) {
            maxLevel = cur;
            max = sum;
        }
    }
    return maxLevel;
}
Also used : TreeNode(hatecode._0001_0999.TreeNode)

Aggregations

TreeNode (com.pkumar7.TreeNode)47 LinkedList (java.util.LinkedList)16 ArrayList (java.util.ArrayList)13 TreeNode (hatecode._0001_0999.TreeNode)11 Stack (java.util.Stack)7 TreeNode (org.apache.myfaces.custom.tree2.TreeNode)6 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)3 List (java.util.List)3 TreeNodeBase (org.apache.myfaces.custom.tree2.TreeNodeBase)3 Account (com.autentia.tnt.businessobject.Account)1 AccountEntry (com.autentia.tnt.businessobject.AccountEntry)1 AccountEntryType (com.autentia.tnt.businessobject.AccountEntryType)1 Activity (com.autentia.tnt.businessobject.Activity)1 AdminHoliday (com.autentia.tnt.businessobject.AdminHoliday)1 Bill (com.autentia.tnt.businessobject.Bill)1 Book (com.autentia.tnt.businessobject.Book)1 BulletinBoard (com.autentia.tnt.businessobject.BulletinBoard)1 BulletinBoardCategory (com.autentia.tnt.businessobject.BulletinBoardCategory)1 CompanyState (com.autentia.tnt.businessobject.CompanyState)1