JZ62 二叉搜索树的第k个结点
本文最后更新于:2022年4月9日 中午
Solution
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
|
class Solution { public: TreeNode* KthNode(TreeNode* pRoot, int k) { if (pRoot == nullptr || k <= 0) return nullptr; stack<TreeNode *> stack; TreeNode* cur = pRoot; while (cur || !stack.empty()) { while (cur) { stack.push(cur); cur = cur->left; } cur = stack.top(); stack.pop(); k--; if (k == 0) return cur; cur = cur->right; } return nullptr; } };
|