I know the idea is to first do level order traversal on the tree.
If the nodes are found on the same level and their parents do not match they are cousins.
And if matches they are siblings.
I can do level order traversal by
BinarySearchTree.prototype.levelOrderTraversal = function() {
var q = [];
var results = [];
var _root = this.root;
if(_root) {
q.push(_root);
while(q.length > 0) {
var temp = q.shift();
results.push(temp.value);
if(temp.left) {
q.push(temp.left);
}
if(temp.right) {
q.push(temp.right);
}
}
return results;
}else {
return null;
}
}
But now how do I keep track of parents so that I can find given nodes are siblings or cousins?
For example,
if my level order traversal gives me
[3, 2, 4, 1, 5]
3 being root, 2 and 4 are siblings or parent 3.
1 is a left child of parent 2.
5 is a right child of parent 4.
so, 1 and 5 are cousin nodes while 2 and 4 are sibling nodes.