Created
August 6, 2018 16:53
-
-
Save ferdelamad/ca4ec90e44da069cc6e77e7e09115c4e to your computer and use it in GitHub Desktop.
kthSmallest InterviewPrepPrompt
This file contains 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
/** | |
* Definition for a binary tree node. | |
* function TreeNode(val) { | |
* this.val = val; | |
* this.left = this.right = null; | |
* } | |
*/ | |
/** | |
* @param {TreeNode} root | |
* @param {number} k | |
* @return {number} | |
*/ | |
//VERSION 1 OF THE SOLUTION | |
/* | |
var kthSmallest = function(root, k) { | |
//input = root tree node, target num | |
//output = target num if found | |
//check if root is the target value | |
if(root.val === k) { | |
return root.val | |
} | |
//results container | |
let result = null; | |
//helper function | |
function checkNode(node, target) { | |
if(node.val === k) { | |
result = node.val | |
return; | |
} else if(node.right) { | |
return checkNode(node.rigth); | |
} else { | |
return checkNode(node.left); | |
} | |
} | |
checkNode(root); | |
return result; | |
}; | |
*/ | |
//VERSION 2 OF THE SOLUTION | |
var kthSmallest = function(root, k) { | |
//input = root tree node, target num | |
//output = target num if found | |
//results container | |
let result = null; | |
//helper function | |
function checkNode(node, target) { | |
if(node.val === target) { | |
result = node.val | |
return; | |
} | |
if (node.right !== null) { | |
checkNode(node.right, target); | |
} | |
if (node.left !== null) { | |
checkNode(node.left, target); | |
} | |
} | |
checkNode(root, k); | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment