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

[LeetCode] 230. Kth Smallest Element in a BST 解题思路

时间:2016-01-10 11:35:01      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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.

 问题:找出二叉搜索树种第 k 小的元素。

一个深度遍历的应用。使用递归、或者借助栈都可以实现深度遍历。本文代码使用递归实现。

 1     void visit(TreeNode* node){
 2         
 3         if (node->left != NULL){
 4             visit(node->left);
 5         }
 6         
 7         if (cnt == 0) {
 8             return;
 9         }
10         
11         cnt--;
12         if(cnt == 0){
13             res = node->val;
14             return ;
15         }
16         
17         if(node->right != NULL){
18             visit(node->right);
19         }
20     }
21 
22     int cnt;
23     int res;
24 
25     int kthSmallest(TreeNode* root, int k) {
26         cnt = k;
27         if(root == NULL){
28             return 0;
29         }
30         visit(root);
31         
32         return (cnt == 0) ? res : 0;
33     }

 

[LeetCode] 230. Kth Smallest Element in a BST 解题思路

标签:

原文地址:http://www.cnblogs.com/TonyYPZhang/p/5117874.html

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