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

LeetCode OJ:Kth Smallest Element in a BST(二叉树中第k个最小的元素)

时间:2015-10-25 13:36:39      阅读:131      评论: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个最小的元素,中序遍历就可以了,具体代码和另一个Binary Tree Iterator差不多其实,这题由于把=写成了==调bug调了好久,细心细心啊啊啊。代码如下:

 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 *> s;
14         map<TreeNode *, bool> m;
15         if(root == NULL) return 0;
16         s.push(root);
17         while(!s.empty()){
18             TreeNode * t = s.top();
19             if(t->left && !m[t->left]){
20                 s.push(t->left);
21                 m[t->left] = true;
22                 continue;
23             }
24             s.pop();  //这里pop
25             k--;
26             if(k == 0)
27                 return t->val;
28             if(t->right && !m[t->right]){
29                 s.push(t->right);
30                 m[t->right] = true;
31             }
32 
33         }
34     }
35 };

 

LeetCode OJ:Kth Smallest Element in a BST(二叉树中第k个最小的元素)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4908566.html

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