230. Kth Smallest Element in a BST

题目[230. Kth Smallest Element in a BST](230. Kth Smallest Element in a 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.

1,利用BST性质

思路:中序遍历是递增的
public class Solution {
   
int count = 0;
int result = Integer.MIN_VALUE;

public int kthSmallest(TreeNode root, int k) {
    traverse(root, k);
    return result;
}

public void traverse(TreeNode root, int k) {
    if(root == null) return;
    traverse(root.left, k);
    count ++;
    if(count == k) result = root.val;
    traverse(root.right, k);       
}
}

你可能感兴趣的:(230. Kth Smallest Element in a BST)