Created
April 25, 2019 17:09
-
-
Save kevinah95/fd88dfd2c8a5eae8d8b871ce75c2446d to your computer and use it in GitHub Desktop.
Inspired in this gist https://gist.github.com/khanov/4f1472b5ae001da817db
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
│ ┌── 8 | |
│ ┌── 6 | |
│ │ └── 5 | |
│ ┌── 5 | |
│ │ │ ┌── 4 | |
│ │ └── 3 | |
│ │ └── 8 | |
└── 2 | |
│ ┌── 5 | |
│ ┌── 6 | |
│ │ └── 4 | |
└── 7 | |
│ ┌── 8 | |
└── 2 | |
└── 5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node{ | |
constructor(value){ | |
this.value = value | |
this.left = null | |
this.right = null | |
} | |
} | |
let buildTreeString = (node, prefix, isTail) =>{ | |
var result = "" | |
if (node.right !== null) { | |
let newPrefix = prefix + (isTail ? "│ " : " ") | |
result += buildTreeString(node.right, newPrefix, false) | |
} | |
result += prefix + (isTail ? "└── " : "┌── ") + node.value + "\n" | |
if (node.left !== null) { | |
let newPrefix = prefix + (isTail ? " " : "│ ") | |
result += buildTreeString(node.left, newPrefix, true) | |
} | |
return result | |
} | |
let node = new Node(2) | |
node.left = new Node(7) | |
node.right = new Node(5) | |
node.left.left = new Node(2) | |
node.left.right = new Node(6) | |
node.left.left.left = new Node(5) | |
node.left.left.right = new Node(8) | |
node.left.right.left = new Node(4) | |
node.left.right.right = new Node(5) | |
node.right.left = new Node(3) | |
node.right.right = new Node(6) | |
node.right.left.left = new Node(8) | |
node.right.left.right = new Node(4) | |
node.right.right.left = new Node(5) | |
node.right.right.right = new Node(8) | |
console.log(buildTreeString(node, "", true)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment