Tree traversal

https://stackoverflow.com/questions/48541996/javascript-tree-traversal-function-error

by Óscar Gómez Alcañiz

HTML

<div id="tree"></div>

SCSS

body {
  font-family: sans-serif;
}

.node {
  text-align: center;
}

.data {
  display: inline-block;
  border: 1px solid black;
  background: yellow;
  border-radius: 50%;
  width: 1em;
  padding: .5em;
}

.left,
.right {
  width: 50%
}

.left {
  float: left;
}

.right {
  float: right;
}

hr {
  width: 50%;
  height: 2em;
  border: 1px solid black;
  margin-top: -.8em;
  margin-bottom: -.8em;
  border-bottom: none;
}

Babel + JSX

class Tree {
  constructor(root) {
    this.root = root;
  }

  Draw(where) {
    let $el = $(where),
      $node = $('<div/>', {
        class: 'node root'
      });

    $node.appendTo($el);

    Tree._Draw(this.root, $node);
  }

  static _Draw(root, $node) {
    let $left,
      $right;

    $node.append(
      $('<span/>', {
        class: 'data'
      }).text(root.data)
    );

    if (root.left || root.right) {
      $node.append($('<hr/>'));
    }

    if (root.left) {
      $left = $('<span/>', {
        class: 'node left'
      });

      $node.append($left);

      Tree._Draw(root.left, $left);
    }

    if (root.right) {
      $right = $('<span/>', {
        class: 'node right'
      });

      $node.append($right);

      Tree._Draw(root.right, $right);
    }
  }

  // Inorder method doesn't need a root argument now
  // It uses instance's own root
  Inorder() {
    // Fire up the recursion
    Tree._Inorder(this.root);
  }

  // Private part for the Inorder method's recursion
  // It can be static since it will receive the root 
  // for each iteration
  static _Inorder(root) {
    if (root == null) {
      return;
    }

    Tree._Inorder(root.left);

    console.log(root.data);

    Tree._Inorder(root.right);
  }
}


class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}

const obj = new Node(5);
obj.left = new Node(10);
obj.right = new Node(15);
obj.left.left = new Node(16);
obj.right.right = new Node(17);
obj.right.left = new Node(8);

const tree = new Tree(obj);
console.log("Tree created with root:", tree.root.data);

// Now we can call the inorder list for the tree 
// without explicitely specifying the root node
tree.Inorder();

tree.Draw('#tree');