algorighm/top-interview-leetcode150/binary-search-tree/230二叉搜索树中第 K 小的元素.js

53 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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}
*/
const kthSmallest = function (root, k) {
};
/*
根据二叉搜索树的特性直接对其进行中序遍历遍历到的第k个数就是第k小这里使用迭代的方式好返回结果
*/
function f1(root, k) {
const stack = []; // 栈用于模拟中序遍历
let node = root; // 从根节点开始遍历
while (node || stack.length > 0) {
// 先处理左子树,将所有左子树节点压入栈中
while (node) {
stack.push(node);
node = node.left;
}
// 弹出栈顶元素并访问
node = stack.pop();
// 递减k如果k为0说明我们已经找到了第k个最小值
if (--k === 0) {
return node.val;
}
// 处理右子树
node = node.right;
}
return null; // 如果没有找到k个元素返回null一般不会发生
}
/*
当一如果当前节点就是目标节点那么它的左子树的数量一定是k-1个如果左子树的数量小于k-1个那么目标节点一定存在右子树中
以当前节点右子树为根节点继续寻找此时k要出去左子树的left加上自己一共left + 1个所以以右子节点为更节点的子树只需寻找
第 k-(left+1)个大的数。使用面向对象的写法封装。
*/
// TODO