DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 54

The task is to return the next sibling, given a DOM tree and a target element.

The boilerplate code

function nextRightSibling(root, target) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

If there is no next sibling, return null

If(!root || !target) return null;
Enter fullscreen mode Exit fullscreen mode

Process the DOM tree level by level. Keep track of the level of the target element.

const queue = [[root, 0]];
  let targetDepth = null;

  while (queue.length) {
    const [node, depth] = queue.shift();

    if (node === target) {
      targetDepth = depth;
      continue;
    }
Enter fullscreen mode Exit fullscreen mode

After the target is found, the next element on the same level as the target is the right sibling. If the next element is on a lower depth, the target has no right sibling

if (targetDepth !== null) {
      if (depth === targetDepth) {
        return node;
      } else if (depth > targetDepth) {
        return null;
      }
    }
Enter fullscreen mode Exit fullscreen mode

The final code

function nextRightSibling(root, target) {
  // your code here
  if(!root || !target) return null;

  const queue = [[root, 0]];
  let targetDepth = null;

  while(queue.length) {
    const [node, depth] = queue.shift();

    if(node === target) {
      targetDepth = depth;
      continue;
    } 
    if(targetDepth !== null) {
      if(depth === targetDepth) {
        return node;
      } else if( depth > targetDepth) {
        return null;
      }
    }
    for(let child of node.children) {
      queue.push([child, depth + 1]);
    }
  }
  return null
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)