Sunday, June 30, 2024

 #codingexercise 

Get the max sum level in a binary tree

int GetMaxLevel(Node root, Node delimiter)

{

List<Integer> nodes = new ArrayList<>() :

if (root == null) return -1;

var q = new Queue<Node>();

q.Enqueue(root);

q.Enqueue(delimiter);

Nodes.add(root):

Nodes.add(delimiter);

var node = q.Dequeue();

while (node)

{

if (node == delimiter) {q.Enqueue(delimiter); nodes.add(delimiter);}

else{

if (node.left) {

      q.Enqueue(node.left) ;

      nodes.add(node.left) :

if (node.right) 

      q.Enqueue(node.right);

      nodes.add(node.right);

}

node = q.Dequeue();

}

var levels = nodes.split(delimiter);

int max  = INT_MIN;

int result =  0;

for (int level = 0; level < levels.Count; level++)

   if (levels[level].Sum > max)

          result = level;

return result;

}

     5

1 3 6 8

 2.    7

Result: 1


No comments:

Post a Comment