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

Kth Smallest Element in a BST

时间:2015-07-07 00:56:35      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

基本思想就是:二叉树的中序非递归遍历

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int kthSmallest(TreeNode* root, int k) {
13         stack<TreeNode *> st;
14         TreeNode * temp=root;
15         int res;
16         int count=0;
17         if(root==NULL)
18             return 0;
19         while(temp!=NULL||!st.empty())
20         {
21             if(temp!=NULL)
22             {
23                 st.push(temp);
24                 if(temp->left!=NULL)
25                     temp=temp->left;
26                 else
27                     temp=NULL;
28             }
29             else if(!st.empty())
30             {
31                 temp=st.top();
32                 st.pop();
33                 count++;
34                 if(count==k)
35                 {
36                     res=temp->val;
37                     break;
38                 }
39                 temp=temp->right;
40             }
41         
42         }
43         return res;
44     }
45     
46 };

 

Kth Smallest Element in a BST

标签:

原文地址:http://www.cnblogs.com/aguai1992/p/4625807.html

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