题解 | #二叉搜索树的第k个节点#
二叉搜索树的第k个节点
https://www.nowcoder.com/practice/57aa0bab91884a10b5136ca2c087f8ff
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ using namespace std; class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param proot TreeNode类 * @param k int整型 * @return int整型 */ int KthNode(TreeNode* proot, int k) { // write code here if (!proot) return -1; stack<TreeNode*> s; TreeNode* p = proot; int cnt = 0; while (p || !s.empty()) { if (p) { s.push(p); p = p->left; } else { p = s.top(); s.pop(); if (++ cnt == k) return p->val; p = p->right; } } return -1; } };