首页 > 其他 > 详细

Kth Smallest Element in a BST

时间:2015-07-07 00:53:31      阅读:325      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!