方法一,中序遍历,所有节点都放入数组,返回第k个。
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
vector<TreeNode*> re;
inorder(pRoot,re);
if(k<1||k>re.size()){
return NULL;
}
return re[k-1];
}
void inorder(TreeNode* pRoot, vector<TreeNode*>& re)
{
if(pRoot!=NULL){
inorder(pRoot->left,re);
re.push_back(pRoot);
inorder(pRoot->right,re);
}
}
};
方法二,计数,返回数目达到第k个时返回。
class Solution {
public:
TreeNode* KthNode(TreeNode* pRoot, int k)
{
//static int i=0;
if(pRoot!=NULL){
TreeNode* p=KthNode(pRoot->left,k);
if(p!=NULL){
return p;
}
++i;
if(i==k){
return pRoot;
}
p=KthNode(pRoot->right,k);
if(p!=NULL){
return p;
}
}
return NULL;
}
private:
int i=0;
};