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 };
时间: 2024-12-24 19:44:49