题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
二叉搜索树的中序遍历可以得到从小到大顺序排列的序列,所以只需要中序遍历二叉树,然后返回第k-1个元素即可。注意考特殊情况
/*
* function TreeNode(x) {
* this.val = x;
* this.left = null;
* this.right = null;
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param proot TreeNode类
* @param k int整型
* @return int整型
*/
function KthNode( proot , k ) {
// write code here
if(!proot || k == 0){
return -1
}
let arr = []
function inOrder(pRoot){
if(!pRoot){
return
}
inOrder(pRoot.left)
arr.push(pRoot.val)
inOrder(pRoot.right)
}
inOrder(proot)
if(k > arr.length){
return -1
}
return arr[k-1]
}
module.exports = {
KthNode : KthNode
};
