Created
April 3, 2017 16:47
-
-
Save twalk4821/0bed6537d9fad0fbdd7f4c346c66896e 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
var kthSmallest = function(binaryTree, k) { | |
var arr = []; | |
var search = function(tree) { | |
if (arr.length<k) { | |
arr.push(tree.value) | |
search(tree.left); | |
search(tree.right); | |
} else { | |
if (tree.value < Math.max(arr)) { | |
arr.splice(arr.indexOf(Math.max(arr))); | |
arr.push(tree.value); | |
search(tree.left); | |
search(tree.right); | |
} | |
} | |
} | |
search(binaryTree); | |
return Math.max(arr); | |
} | |
var kthSmallest = function(tree, k) { | |
if (tree.children === null) { | |
return tree.value | |
} else { | |
return Array.reduce([kthSmallest(tree.left), tree.value, kthSmallest(tree.right)], function(acc, next) { | |
if (acc>next && acc[0]<k) { | |
acc[0]++; | |
acc[1] = y; | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment