-
Notifications
You must be signed in to change notification settings - Fork 270
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
3 New Problems on BST #63
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If a node is not found then return array should be empty in find-ancestors
but it return array values where it visited.
I have re-implemented it. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
find-ancestors
search whole BST tree. Implementation should be done in O(logn(n)) time.
You can use this code...
function findAncestors(root, value) {
/**
* search the given node and meanwhile
* keep pushing the visited nodes
*/
if (root === null) return false;
if (value < root.value) {
const left = findAncestors(root.leftChild, value);
if (left) {
return [...left, root.value];
}
return false;
}
if (value > root.value) {
const right = findAncestors(root.rightChild, value);
if (right) {
return [...right, root.value];
}
return false;
}
if (value === root.value) return [];
return false;
}
I am both sad and happy, happy coz at least reached the best way using recursion in the first go, sad because I messed up with the edge case. 👥 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💯
🌳 What's Inside?
findAncestors()
to find all the ancestors of a given node.findHeightOfBST()
to find all the ancestors of a given node.findKNodes()
to find all the nodes k distance away from the root.