Amazon Interview Question
SDE1sCountry: India
Interview Type: In-Person
O(N) and O(1) for storage, of course, the recursive implementation is kinda expensive while the tree is deep because of the stacks stored while making recursive calls.
@suzker-U r logic is right but the code u have provided will not print anything for any input
The idea is right. You should add:
count = (count >= 1) ? count : 1;
before the if clause for it to work.
Complexity O(n)
public List getListOfNodes(Node root,int k)
{
ArrayList<Node> list= new ArrayList<Node>()
getLeaves(root,list,k);
return list;
}
public int getLeaves(Node node,ListnNode[] nodeList,int k)
{
int numLeafL,numLeafR=0
if(node.getLeft==null && node.getRight==null)
{
return 1;
}
if(node.getLeft)
{
numleafL=getLeaves(node.getLeft);
}
if(node.getRight)
{
numleafR=getLeaves(node.getRight);
}
currentLeafcount=numLeafL+numRight;
if(currentLeafCount==k)
{
nodeList.add(node)
}
return currenLeafCount;
}
We have to use Bottom up approach
1. Traverse the tree in postorder manner.
2.While traversing keep count of the leaf nodes
3. add nodes who have k leaves to list
4. At the end LIst will contain the ans
int getNodeWithKLeaves(Node root,int k,LinkedList<Integer> list)
{
if(root==null)
return 0;
int x=0;
x+=getNodeWithKLeaves(root.left, k, list);
x+=getNodeWithKLeaves(root.right, k, list);
if(root.left==null&&root.right==null)
x++;
if(k==x)
list.add(root.info);
return x;
}
why is
if(root.left==null&&root.right==null)
x++;
statement required just do
if(x==0) x++; at the same place
@kkr.ashish U checked x==0 which means there is no leaf node to that particular node that means it is a leaf node itself and i m also checking the same so it is the two different ways of doing same thing
it can be done with a modified post-order traverse. To simplify things, i'll put it in recursive style:
- suzker January 22, 2014