230.二叉树中第K小元素
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function (root, k) {
// 搜索二叉树的中序遍历一定是升序
let res = []
// 中序遍历(左中右)
function inorder(root) {
if (!root) {
return
}
inorder(root.left) // 左
res.push(root.val) // 中
inorder(root.right) // 右
}
inorder(root)
console.log(res)
return res[k - 1]
};
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
// 优化 使用常量
var kthSmallest = function (root, k) {
// 搜索二叉树的中序遍历一定是升序
let count = 0
let res = null
// 中序遍历(左中右)
function inorder(root) {
if (!root) { // 递归结束条件
return
}
if(res) { // 找到第k小值了,结束递归
return
}
inorder(root.left) // 左
count++ // 中
if(count === k) {
res = root.val
}
inorder(root.right) // 右
}
inorder(root)
return res
};