Amazon Interview Question
SDE1sCountry: India
Interview Type: In-Person
Node exploreAll (Node root, int sum, int val ) {//val is the threshold value set
if (root == null)
return root;
Node LC = root.left;
Node RC = root.right;
if ( LC!= null )
Node status1 = exploreAll (LC,sum+root.data,val);
if ( RC != null )
Node status2 = exploreAll (RC,sum+root.data,val); //can store root.data in a temporary variable to save one computation.//
checkLeft (status1, root, RC, LC);
checkRight (status2, root, LC, RC);
if ( LC == null && RC == null ) {
if ( sum + root.data < val ) {
root = null;
return root;
}
}
return root;
}
void checkLeft (Node status1, Node root, Node RC, Node LC) {
if ( root != null && status1 == null ) {
if ( RC != null ) {
if ( root.parent != null ) {
if ( root.parent.left == root )
root.parent.left = RC;
else
root.parent.right = RC;
}
else {
Node newNode = new Node ();
newNode.left = LC;
newNode.right = RC;
}
}
}
root = null;
}
void checkRight (Node status2, Node root, Node LC, Node RC) {
if ( root != null && status2 == null ) {
if ( LC != null ) {
if ( root.parent != null ) {
if ( root.parent.left == root )
root.parent.left = LC;
else
root.parent.right = LC;
}
else {
Node newNode = new Node ();
newNode.left = LC;
newNode.right = RC;
}
}
}
root = null;
}
- Suman March 05, 2014