Find the nearest right node in a binary tree

Jyothi
2 min readMar 24, 2022

--

One thing we should always remember in case of trees. A tree is also a graph, so there are 2 types of possible traversals : DFS and BFS. DFS traversals can be pre-order traversal, in-order traversal and post order traversal.
In case of BFS, we always need to gather a set of nodes which are on same level. We may need a data structure of queue to gather these nodes and then to go for the next set of nodes.

This problem is to find a next right node on same level. So, BFS is right traversal for it. We can also go for DFS too.
When using DFS we use space of recursive stack.
When using BFS we use extra Queue space instead of recursive stack.
Please comment if we can avoid both these extra spaces.

Below is the DFS based solution:

struct TreeNode* findParentOrRight(struct TreeNode* root, struct TreeNode* u, int lvl);int node_found = 0;
bool rfound =0;
struct TreeNode* findNearestRightNode(struct TreeNode* root, struct TreeNode* u){
int lvl = 0;
struct TreeNode *rt;
rfound = 0;
node_found = 0;
rt = findParentOrRight(root, u, lvl);
if (rfound) return rt;
return NULL;
}
/* this function is goes into depth and try to find a matching node of u
then find another node with the same depth
Here to avoid 2 arguments to function, we are using 2 global variables.
This func should be called only sequentially */
struct TreeNode* findParentOrRight(struct TreeNode* root, struct TreeNode* u, int lvl){
struct TreeNode *ret = NULL;
/* if root is u, no rightmost node in same level */
if (!root || !u || (root == u))
return NULL;

/* if node found and right node to be found */
if ((node_found) && (lvl== node_found)) {
rfound = 1; return root;
}
/* if u matching with root->left and root->right not NULL , return */
if (root->left == u){
node_found = lvl+1;
if (root->right){ rfound = 1; return root->right; }
/* if no right node, return parent */
return root;
}
if (root->right == u){
node_found = lvl+1; return root;}

if (root->left) {
ret = findParentOrRight(root->left, u, lvl+1);
}

/* if right node found */
if (rfound) return ret;

if (root->right)
ret = findParentOrRight(root->right, u, lvl+1);

return ret;
}

BFS approach:

struct TreeNode* findNearestRightNode(struct TreeNode* root, struct TreeNode* u){
int num = 1;

struct TreeNode ** Q, **newQ, *nd;

int nQ,ii, nnQ;

if (!root || !u)
return NULL;

nQ = 1;
Q = (struct TreeNode **)malloc(sizeof(struct TreeNode *));
// todo check
Q[0] = root;
int mnodes = 1;

do {
mnodes <<=1;
newQ = (struct TreeNode **)malloc(mnodes*sizeof(struct TreeNode *));
// todo check
nnQ=0;
for (ii=0; ii<nQ; ii++){
nd = Q[ii];
if (nd == u){
if (ii < (nQ-1))
return Q[ii+1];
return NULL;
}
if (nd->left)
newQ[nnQ++] = nd->left;
if (nd->right)
newQ[nnQ++] = nd->right;
}
free(Q);
Q = newQ;
nQ = nnQ;

}while (nnQ);
return NULL;
}

Please give your comments or feedback. Where are all we can optimize.

--

--

No responses yet