Open In App

Find the Preorder Successor of a Given Node in a Binary Tree using JavaScript

The Preorder successor of a given node is a node that occurs after the given node in the preorder traversal of the binary tree. The preorder traversal is a traversal in which the root node is visited first, then the left child, and then the right child.

Example:

The pre-order successor of a binary tree is given by Root, Left, and Right.

Binary-Tree-

The preorder traversal of the above binary tree is: 1, 2, 4, 5, 3, 6, 7.

Using Binary Tree Traversal

The code defines a Vertex class representing a binary tree node with key, left, right, and parent pointers. The presuccessor function determines the preorder successor of a given node, considering its children and parent relationships. It constructs a binary tree and finds the preorder successor of a selected node. Finally, it prints the result, indicating the preorder successor if found or null otherwise. The code efficiently navigates the tree, handling cases where nodes have left or right children, or no children at all. It provides a robust solution for finding preorder successors in binary trees using JavaScript.

Example: This example shows the use of the above-explained approach.

class Vertex {
    constructor(key) {
        this.key = key;
        this.left = this.right = this.parent = null;
    }
}

function presuccessor(root, v) {
    if (v.left) return v.left;
    if (v.right) return v.right;

    let current = v,
        parent = current.parent;
    while (parent && parent.right === current) {
        current = parent;
        parent = parent.parent;
    }
    return parent ? parent.right : null;
}

// Create the binary tree
let root = new Vertex(1);
root.left = new Vertex(2);
root.left.left = new Vertex(4);
root.left.right = new Vertex(5);
root.right = new Vertex(3);
root.right.left = new Vertex(6);
root.right.right = new Vertex(7);

// Set parent pointers
root.left.parent = root;
root.left.left.parent = root.left;
root.left.right.parent = root.left;
root.right.parent = root;
root.right.left.parent = root.right;
root.right.right.parent = root.right;

// Find the preorder successor and print the result
let node = root.left.right;
let successor = presuccessor(root, node);
if (successor) {
    console.log("Preorder Successor of " + node.key + " is " + successor.key);
} else {
    console.log("Preorder successor of " + node.key + " is null");
}

Output
Preorder Successor of 5 is 3
Article Tags :