leetcode 230. Kth Smallest Element in a BST 二叉搜索树BST的中序遍历是有序序列

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.

Follow up:
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

考察要点:二叉搜索树BST的中序遍历可以得到一个有序的序列。

所以DFS深度优先遍历遍历即可。

代码如下:

import java.util.ArrayList;

/*class TreeNode 
{
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
}*/

/*
 * 这道题的关键就是BST的中序遍历得到的就是排序好的数组
 * 这个是k小元素,我们的得到的是从小到大的元素(优先遍历左结点,然后右结点)
 * 假如是k大元素,直接邮箱遍历右结点,然后是左结点,同样如此
 * 
 * */
public class Solution 
{
    public int kthSmallest(TreeNode root, int k) 
    {
        if(root==null || k<=0)
            return -1;
        ArrayList<Integer> one=new ArrayList<>();
        getKSmall(root,one,k);       
        return one.get(k-1);
    }

    public void getKSmall(TreeNode root, ArrayList<Integer> one,int k) 
    {
        if(root!=null)
        {
            getKSmall(root.left, one,k);

            one.add(root.val);
            if(one.size()==k)
                return;

            getKSmall(root.right, one,k);
        }
    }
}

下面是C++的做法,就是一个简单的DFS深度优先遍历的应用,

这道题最重要的事情就是要记住BFS二叉搜索树的中序遍历的结果是一个有序序列

代码如下:

#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <string>
#include <map>

using namespace std;

/*
struct TreeNode 
{
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
*/

class Solution
{
public:
    vector<int> res;
    int kthSmallest(TreeNode* root, int k)
    {
        getAll(root, k);
        return res[k - 1];
    }

    void getAll(TreeNode* root, int k)
    {
        if (root != NULL)
        {
            getAll(root->left,k);
            res.push_back(root->val);
            if (res.size() == k)
                return;
            getAll(root->right,k);
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值