LeeCode-刷题日记-Day30

230. 二叉搜索树中第K小的元素

思路:遍历二叉树的所有节点,将其存储在一个数组中,再将数组排序。即可拿到第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 preOrder(root){
        if(root){
            res.push(root.val);
            preOrder(root.left);
            preOrder(root.right);
        }
    }
    preOrder(root);
    res.sort((a,b)=>a-b);
    return res[k-1];
};

173. 二叉搜索树迭代器

思路:中序遍历,将其结果存入数组中。

/**
 * 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
 */
var BSTIterator = function(root) {
    this.index=0;
    this.arr=[];
    inOrder(root,this.arr);
};

/**
 * @return {number}
 */
BSTIterator.prototype.next = function() {
    return this.arr[this.index++];
};

/**
 * @return {boolean}
 */
BSTIterator.prototype.hasNext = function() {
    return this.index<this.arr.length;
};
function inOrder(root,arr){
    if(root){
        inOrder(root.left,arr);
        arr.push(root.val);
        inOrder(root.right,arr);
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * var obj = new BSTIterator(root)
 * var param_1 = obj.next()
 * var param_2 = obj.hasNext()
 */