Skip to content

Instantly share code, notes, and snippets.

@dhananjay431
Last active December 18, 2021 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhananjay431/b1eb9006b657ace69fd6f6c54c3bfb5f to your computer and use it in GitHub Desktop.
Save dhananjay431/b1eb9006b657ace69fd6f6c54c3bfb5f to your computer and use it in GitHub Desktop.
tree_js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="./src/lodash.js"></script>
<script>
let rn = (d) => Math.floor(Math.random() * d)
let getarr = (l, m) => Array(l).fill(0).map(x => rn(m));
class node {
constructor(num) {
this.num = num;
this.left = null;
this.right = null;
}
}
function add(n, num) {
let t = new node(num);
if (n.num > num && n.left == null) {
n.left = new node(num);
}
else {
if (n.num > num && n.left != null) {
add(n.left, num);
}
else {
if (n.num < num && n.right == null) {
n.right = new node(num);
}
else {
if (n.num < num && n.right != null) {
add(n.right, num);
}
}
}
}
return n;
}
function dis_json(n, obj) {
obj.num = n.num;
if (n.left != null) {
// obj.left = {};
obj.left = dis_json(n.left, {});
}
if (n.right != null) {
//obj.right = {};
obj.right = dis_json(n.right, {});
}
return obj;
}
function dis_l(n, arr) {
// console.log(n.num);
arr.push(n.num);
if (n.left != null) {
dis_l(n.left, arr);
}
if (n.right != null) {
dis_l(n.right, arr);
}
return arr;
}
function dis_r(n, arr) {
arr.push(n.num);
if (n.right != null) {
dis_r(n.right, arr);
}
if (n.left != null) {
dis_r(n.left, arr);
}
return arr;
}
/* console.log(add(add(add(add(new node(6),5),7),9),3)) */
let arr = getarr(30, 999999)
console.log("raw arr=>", arr);
var root = new node(arr[0]);
for (var i = 1; i < arr.length; i++) {
root = add(root, arr[i])
}
console.log("root=>", root);
console.log("sorted=>", _.sortBy(arr));
console.log("tree l=>", dis_l(root, []));
console.log("tree r=>", dis_r(root, []));
// console.log("tree dis_json=>", JSON.stringify(dis_json(root, {}), null, 4));
console.log("tree dis_json=>", dis_json(root, {}));
</script>
<title>tree_js</title>
</head>
<body></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment