Binary Tree

The simplest binary tree possible . With print function. I've used recursion on this code cause I wanted to make it simple, but I know for larger trees it might blow the stack call.

by Victor Ribeiro

JavaScript

class Node {

	constructor(val){
		this.val = val
		this.c = 1
		this.l = null
		this.r = null
		this.v = false
	}

	add(node){
		if( node.val < this.val ){
			if( !this.l ){
				this.l = node
			}else{
				this.l.add( node )
			}
		}else if( node.val > this.val ){
			if( !this.r ){
				this.r = node
			}else{
				this.r.add( node )
			}
		}else{
			this.c += 1
		}
	}

	print(){
		if( !this.v ){
			this.v = true
			if( this.l ) this.l.print()
			for(let i = 0; i < this.c; i++)
				document.write( this.val+"<br>" )
			if( this.r ) this.r.print()
			this.print()
		}
	}

}

const t = new Node(16)
const n1 = new Node(23)
const n2 = new Node(100)
const n3 = new Node(5)

t.add(n1)
t.add(n2)
t.add(n3)

t.add( new Node(1) )

t.add( new Node(1) )

t.print()