码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 230. Kth Smallest Element in a BST

时间:2019-12-07 10:18:19      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:root   tree   void   private   always   treenode   ini   arc   elements   

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.

Example 1:

Input: root = [3,1,4,null,2], k = 1
   3
  /  1   4
     2
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      /      3   6
    /    2   4
  /
 1
Output: 3

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     int res;
12     int count;
13     public int kthSmallest(TreeNode root, int k) {
14         res = 0;
15         count = k;
16         inOrder(root);
17         return res;
18     }
19     
20     private void inOrder(TreeNode root) {
21         if (root == null) {
22             return;
23         }
24         inOrder(root.left);
25         count -= 1;
26         if (count == 0) {
27             res = root.val;
28             return;
29         }
30         inOrder(root.right);
31     }
32 }

 

[LC] 230. Kth Smallest Element in a BST

标签:root   tree   void   private   always   treenode   ini   arc   elements   

原文地址:https://www.cnblogs.com/xuanlu/p/12000770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!