我越来越菜了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class Solution { public: int kthSmallest(TreeNode* root, int k) { stack<TreeNode*> s; s.push(root); TreeNode* cur = root; int i{ 0 }; while(cur || !s.empty()) { while(cur) { s.push(cur); cur = cur->left; } cur = s.top(); s.pop(); if(++i == k) return cur->val; cur = cur->right; } return 0; } };
|
in-order 遍历就是从小到大的排序,因此只需要进行in-order遍历
中序遍历中先把最左边的加进栈,然后走一个节点的右边。当没有右树的就会进入下一个循环走到上一个树
inorder递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public: int kthSmallest(TreeNode* root, int k) { int ret; inorder(root, ret, k); return ret; } private: void inorder(TreeNode* root, int& ret, int& k) { if(!root) return; inorder(root->left, ret, k); if(--k == 0) { ret = root->val; return; } inorder(root->right, ret, k); } };
|