Created
June 13, 2018 19:05
-
-
Save pinkmomo027/8a6262c9b7d4bfc9d5bbe81c03ce4f33 to your computer and use it in GitHub Desktop.
standard recursive, one run, LCA
This file contains hidden or 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 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); |
Author
pinkmomo027
commented
Jun 13, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment