Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

demonstrate preorder , postorder and inorder traversal in tree

 class Node {

  constructor(value) {

    this.value = value;

    this.left = null;

    this.right = null;

  }

}

 

class BinaryTree {

  constructor() {

    this.root = null;

  }

 

  insert(value) {

    const node = new Node(value);

    if (!this.root) {

      this.root = node;

      return this;

    }

    let current = this.root;

    while (true) {

      if (value < current.value) {

        if (!current.left) {

          current.left = node;

          return this;

        }

        current = current.left;

      } else if (value > current.value) {

        if (!current.right) {

          current.right = node;

          return this;

        }

        current = current.right;

      } else {

        return undefined;

      }

    }

  }

 

  preorder(node = this.root) {

    if (node) {

      console.log(node.value);

      this.preorder(node.left);

      this.preorder(node.right);

    }

  }

 

  inorder(node = this.root) {

    if (node) {

      this.inorder(node.left);

      console.log(node.value);

      this.inorder(node.right);

    }

  }

 

  postorder(node = this.root) {

    if (node) {

      this.postorder(node.left);

      this.postorder(node.right);

      console.log(node.value);

    }

  }

}

 

const tree = new BinaryTree();

tree.insert(10);

tree.insert(6);

tree.insert(15);

tree.insert(3);

tree.insert(8);

tree.insert(12);

tree.insert(18);

 

console.log('Preorder:');

tree.preorder();

 

console.log('Inorder:');

tree.inorder();

 

console.log('Postorder:');

tree.postorder();

 

Output:-

Preorder:

10

6

3

8

15

12

18

Inorder:

3

6

8

10

12

15

18

Postorder:

3

8

6

12

18

15

10

Post a Comment

0 Comments

Ad Code

Responsive Advertisement