您的位置:首页 > 其它

230. Kth Smallest Element in a BST(1)

2016-03-14 13:14 288 查看
/**not ac
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
if(!root) return 0;
stack<TreeNode*> s1;
s1.push(root);//wrong
while(root||!s1.empty())
{
while(root)
{
s1.push(root);
root=root->left;
}
root=s1.top();
s1.pop();
k--;
if(!k) return root->val;
if(root->right) root=root->right;
}

}
};

/**ac 20ms
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
if(!root) return 0;
stack<TreeNode*> s1;
while(root||!s1.empty())
{
while(root)
{
s1.push(root);
root=root->left;
}
root=s1.top();
s1.pop();
k--;
if(!k) return root->val;
root=root->right;
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: