题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
/* * 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 const result = [] dfs(proot, result) if (k > result.length || proot === null || k <= 0) return -1 return result[k - 1] } function dfs(node, array) { if (node === null) return const left = node.left dfs(left, array) array.push(node.val) const right = node.right dfs(right, array) } module.exports = { KthNode : KthNode };