LeetCode-230 kth smallest element in a bst 二叉搜索树中第K小的元素

版权声明:转载请注明原址,有错误欢迎指出 https://blog.csdn.net/iwts_24/article/details/83544839

题目链接

https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/

题意

中文题,对于二叉搜索树而言,找其中的第K小的数

题解

        很有趣的题,但是很简单,实际上就是对树的中序遍历,关于第K小,因为是二叉搜索树,所以最左边的就是最小的,那么中序遍历的情况下,第一次回溯到中序就是最小的一个节点,从该节点开始判定index累加,当index == K的时候,该节点就是第K小了。主要还是考察了二叉搜索树的概念吧。

        注意剪枝,适当剪枝能显著提升速度,例如找到第K小以后设置flag,直接结束遍历。

Java 代码

class Solution {
    public static int index;
    public static int ans;
    public static int flag;
    public static int now;

    public static void solve(TreeNode root){
        if(root.left != null){
            solve(root.left);
        }
        now++;
        if(flag == 1) return;
        if(now == index){
            flag = 1;
            ans = root.val;
            return;
        }
        if(root.right != null){
            solve(root.right);
        }

    }

    public int kthSmallest(TreeNode root, int k) {
        index = k;
        flag = 0;
        now = 0;
        solve(root);
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/iwts_24/article/details/83544839