You are on page 1of 3

1.

True or False: At least half of the nodes in a Heap are


“leaves”. Explain.?
True
A heap is a tree-based data structure in which all the nodes of the
tree are in a specific order.

For example, if X is the parent node of Y, then the value of X follows
a specific order with respect to the value of Y and the same order will
be followed across the tree.
Suppose there are N Jobs in a queue to be done, and each job has its
own priority. The job with maximum priority will get completed first
than others. At each instant, we are completing a job with maximum
priority and at the same time we are also interested in inserting a
new job in the queue with its own priority.
Consider the below binary heap
The above heap tree contains total 7 nodes, in that 4 are leaves. If to
take any binary heap node, always half of the nodes will be leaves.
Caution: If the heap does not follow binary tree, then this may not
come satisfy the condition

2. Explain why the interface for a Heap resembles that of


a Stack, (as opposed to a List).

In java there are two places where an object can be stored the heap
and the stack. Objects allocated on the stack are available only inside
of a stack frame(execution of a method), while objects allocated on
the heap can be accessed from anywhere.

Reference types (classes, interfaces, delegates) are always allocated


on the heap. When you pass a reference object as a parameter or
assign it to a variable, you're in fact passing its reference. The
reference (not the referenced object) can be allocated both on the
stack or on the heap. By passing a reference to an object, you're
telling where that object is located on the heap so that your code can
access it.

Every time an object is passed as a reference, the reference itself is


copied. This means that you can change the reference to point to a
different object without affecting the previous object itself or other
references pointing to it.

Value types (derived from System.ValueType,


e.g. int, bool, char, enum and any struct) can be allocated on the
heap or on the stack, depending on where they were declared.
 If the value type was declared as a variable inside a method
then it's stored on the stack.
 If the value type was declared as a method parameter then
it's stored on the stack.
 If the value type was declared as a member of a class then it's
stored on the heap, along with its parent.
 If the value type was declared as a member of a struct then
it's stored wherever that struct is stored.
a struct can be declared as ref struct, in which case it will always be
allocated on the stack, preventing it from being declared inside
reference types.
Instances of value types are passed by copy. This means that every
time a value type is assigned to a variable or passed as parameter,
the value is copied.

You might also like