白菜刷LeetCode记-230. Kth Smallest Element in a BST

今天的题目如下:

这题目是要找出二叉搜索树第k个小的节点并返回其值。那么首先就要看看什么是二叉搜索树。二叉搜索树的特征如下:

1、所有非叶子节点至多拥有两个儿子;

2、所有节点存储一个关键字;

3、非叶子节点的左边指针指向小于其关键字的子树,右边指向大于其关键字的子树。

 

根据上面的特征,我们使用中序遍历树就可以了,代码如下:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
var idx = 0;
var res = null;

var kthSmallest = function(root, k) {
    idx = 0;
    helper(root, k)
    return res;
};



var helper = function(node,k){
    if(node == null && res != null){
        return;
    }
    
    if(node.left != null){
        helper(node.left,k);
    }
    
    if(++idx == k){
        res = node.val;
    }
    
    if(node.right != null){
        helper(node.right,k);
    }
}

 

好了,今天就到这里吧。

posted @ 2018-09-17 15:23  sysu_kww  阅读(93)  评论(0编辑  收藏  举报