Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Created June 13, 2018 19:05
Show Gist options
  • Save pinkmomo027/8a6262c9b7d4bfc9d5bbe81c03ce4f33 to your computer and use it in GitHub Desktop.
Save pinkmomo027/8a6262c9b7d4bfc9d5bbe81c03ce4f33 to your computer and use it in GitHub Desktop.
standard recursive, one run, LCA
class BNode {
constructor (value) {
this.data = value;
this.left = null;
this.right = null;
}
search(values) {
let c = values.indexOf(this.data) >=0 ? 1 : 0;
let lc = this.left ? this.left.search(values) : 0;
let rc = this.right? this.right.search(values) : 0;
return c + lc + rc;
}
searchLCA(values) {
if (values.indexOf(this.data) >= 0) {
return this;
}
//search left tree
if (this.left) {
let leftCount = this.left.search(values);
if (leftCount == values.length) {
return this.left.searchLCA(values);
}
if (leftCount == 0 && this.right) {
return this.right.searchLCA(values);
}
if (leftCount > 0 && leftCount < values.length) {
return this;
}
}
return "Not Found";
}
searchLCA2(node, v1, v2) {
if (node == null) {
return null;
}
if (node.data == v1 || node.data == v2) {
return node;
}
let leftLCA = this.searchLCA2(node.left, v1, v2);
let rightLCA = this.searchLCA2(node.right, v1, v2);
if (leftLCA && rightLCA) {
return node;
}
return leftLCA ? leftLCA : rightLCA;
}
}
let root = new BNode(0);
let l1 = new BNode(10);
let l2 = new BNode('A');
root.left = l1; root.right = l2;
let p1 = new BNode(100);
let p2 = new BNode(27);
l1.left = p1; l1.right = p2;
let p3 = new BNode("X");
let p4 = new BNode("YY");
l2.left = p3; l2.right = p4;
p4.left = new BNode("horse")
console.log(root.searchLCA2(root, 100, 27));
console.log(root.searchLCA2(root, "horse", "X"));
console.log(root.searchLCA2(root, "A", "YY"));
console.log("-----ROOT------");
console.log(root);
@pinkmomo027
Copy link
Author

BNode {
  data: 10,
  left: BNode { data: 100, left: null, right: null },
  right: BNode { data: 27, left: null, right: null } }
BNode {
  data: 'A',
  left: BNode { data: 'X', left: null, right: null },
  right:
   BNode {
     data: 'YY',
     left: BNode { data: 'horse', left: null, right: null },
     right: null } }
BNode {
  data: 'A',
  left: BNode { data: 'X', left: null, right: null },
  right:
   BNode {
     data: 'YY',
     left: BNode { data: 'horse', left: null, right: null },
     right: null } }
-----ROOT------
BNode {
  data: 0,
  left:
   BNode {
     data: 10,
     left: BNode { data: 100, left: null, right: null },
     right: BNode { data: 27, left: null, right: null } },
  right:
   BNode {
     data: 'A',
     left: BNode { data: 'X', left: null, right: null },
     right: BNode { data: 'YY', left: [BNode], right: null } } }
[Finished in 0.1s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment