DEV Community

almokhtar bekkour
almokhtar bekkour

Posted on

Modify a binary tree to get Preorder traversal using right pointers only

To modify a binary tree to perform a preorder traversal using only the right pointers, you will need to make some changes to the tree structure and the traversal algorithm. Here is one way you could approach this problem:

In the binary tree, add a new pointer to each node that points to the node's rightmost descendant (or null if the node has no right descendants). This pointer will be used during the traversal instead of the node's right pointer.

Write a function to perform the preorder traversal. This function should start at the root node and visit the nodes in the following order: the root, the root's left child, the root's left child's left child, etc. until it reaches a leaf node.

At each step of the traversal, the function should use the new rightmost descendant pointer to move to the next node in the traversal. If the current node has no rightmost descendant, the function should backtrack to the nearest ancestor that has a rightmost descendant and move to that descendant.

The traversal should continue until it has visited all of the nodes in the tree.

Here is an example of what the main parts of your solution might look like:


class Node {
  constructor(value) {
    this.value = value
    this.left = null
    this.right = null
    this.rightmost = null // new pointer to rightmost descendant
  }
}

class BinaryTree {
  // initialize the tree and set the root node

  traversePreorder() {
    // perform a preorder traversal using only the rightmost pointers

    // return the list of nodes visited in preorder
  }
}

const tree = new BinaryTree(...)
const preorder = tree.traversePreorder()

// display the preorder traversal

Enter fullscreen mode Exit fullscreen mode

You may need to modify the tree structure and the traversal algorithm depending on the specific requirements of your problem.

Top comments (0)