【问题】给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)中,按结点数值大小顺序第三小结点的值为4。
【思路】由于根据二叉搜索树的特性,其中序遍历正好是一个排好序的序列,从小到大依次排序,因此其第k个最小节点则为数组第k-1个数(数组从零开始索引)。一般功能修改的话,建议在非递归遍历版本进行修改,其思路更加清晰,我们只需要设置一个索引index,stack每次做pop操作后,让index+1,如果等于k,则输出节点即可!
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: TreeNode* KthNode(TreeNode* pRoot, int k) { if(pRoot == nullptr) return nullptr; stack<TreeNode*> sta; TreeNode* cur = pRoot; int index = 1; while(!sta.empty() || cur != nullptr){ if(cur != nullptr){ sta.push(cur); cur = cur->left; }else{ cur = sta.top(); sta.pop(); if(index++ == k){ return cur; } cur = cur->right; } } return nullptr; } };