Created
January 10, 2019 05:47
-
-
Save kevinahn7/c0496da1607cd812a2d42f17e80ff8de to your computer and use it in GitHub Desktop.
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
| function pathToX(root, x) { | |
| if (root === null) { | |
| return null; | |
| } | |
| if (root.value === x) { | |
| return [x]; | |
| } | |
| let leftPath = pathToX(root.left, x); | |
| if (leftPath !== null) { | |
| leftPath.shift(root.value); | |
| return leftPath; | |
| } | |
| let rightPath = pathToX(root.right, x); | |
| if (rightPath !== null) { | |
| rightPath.shift(root.value); | |
| return rightPath; | |
| } | |
| return null; | |
| } | |
| function LCA(root, j, k) { | |
| let pathToJ = pathToX(root, j); | |
| let pathToK = pathToX(root, k); | |
| let LCAToReturn; | |
| while (pathToJ.length > 0 && pathToK.length > 0) { | |
| let jNumber = pathToJ.shift(); | |
| let kNumber = pathToK.shift(); | |
| if (jNumber === kNumber) { | |
| LCAToReturn = kNumber; | |
| } else { | |
| break; | |
| } | |
| } | |
| return LCAToReturn; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment