## Interview Question

Country: India
Interview Type: In-Person

Comment hidden because of low score. Click to expand.
0
of 0 vote

maintain a max heap with pair<height, val>, keep popping and adding val till height is of max value.

Comment hidden because of low score. Click to expand.
0
of 0 vote

To calculate sum of all leaves in a Tree i use modified traverse function. The function is recursive, first it calculates the sum of leaves in left subTree of a node, then the leaves of right subTree, and then returns sum of left + right. To identify a leaf node it checks if its leftChild and rightChild are null. If they are null it returns a value of current node. The code is in java. To make code simpler i use only Node class without tree.

``````public class SumLeafExample{

public static class Node{
private int key;
private Node left;
private Node right;

public Node(int key)
{
this.key = key;
this.left = null;
this.right = null;
}

public void insert(int key)
{
insert(key, this);
}

private void insert(int key, Node localRoot)
{
if(key < localRoot.key)
{
if(localRoot.left != null)
{
insert(key, localRoot.left);
}else
{
localRoot.left = new Node(key);
}
}else
{
if(localRoot.right != null)
{
insert(key, localRoot.right);
}else
{
localRoot.right = new Node(key);
}
}
}

public int leafSum()
{
return leafSum(this);
}

private int leafSum(Node localRoot)
{
if(localRoot == null)return 0;
if(localRoot.left == null && localRoot.right == null)
{
return localRoot.key;
}else
{
int leftSum = leafSum(localRoot.left);
int rightSum = leafSum(localRoot.right);
return leftSum + rightSum;
}
}
}

public static void main(String []args){
Node treeRoot = new Node(20);
treeRoot.insert(10);
treeRoot.insert(30);
treeRoot.insert(18);
treeRoot.insert(29);
treeRoot.insert(45);

System.out.println(treeRoot.leafSum());
//18 + 29 + 45 = 92
}
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.