題目描述
思路:二叉搜索樹的一個重要性質就是它的中序遍歷是排序的,因此這道題目只需要用中序遍歷算法遍歷一棵二叉搜索樹,就很容易找出它的第K大結點。中序遍歷用遞歸實現比較容易,但要想清楚的是遍歷到一個根結點的時候要做的是什麼?中序遍歷二叉樹打印的時候我們在遞歸完左子樹之後打印根結點,本題目要求的當然不是打印,如果左子結點不是要找的結點,纔會訪問根結點,所以訪問到根結點的時候要做的操作是將k減去1,因爲左子結點已經證實不是要找的結點了,排除左子結點。這個過程可以看成目標移位的過程,每移過一個結點,K減1,直到K等於1時,當前結點就是要求的結點。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
int c=0;
TreeNode* KthNodecore(TreeNode* pRoot,int &k){//中序遍歷
TreeNode* t=nullptr;
if(pRoot->left){
t=KthNodecore(pRoot->left,k);
}
if(t) return t;
c++;
if(c==k) return pRoot;
if(!t&&pRoot->right){
t=KthNodecore(pRoot->right,k);
}
if(t) return t;
return nullptr;
}
/*TreeNode* target=nullptr;
if(pRoot->left){//遍歷左子樹
target=KthNodecore(pRoot->left,k);
}
if(!target){
if(k==1)
target=pRoot;
k--;
}
if(!target&&pRoot->right)//遍歷右子樹
target=KthNodecore(pRoot->right,k);
return target;
}*/
TreeNode* KthNode(TreeNode* pRoot, int k)
{
if(!pRoot||k<1) return nullptr;
return KthNodecore(pRoot,k);
}
};