題目
給定一棵二叉搜索樹,請找出其中第k大的節點。
題解
好久沒打代碼了,練練手,知識點題目,中序遍歷。
遞歸
class Solution {
public:
int ans = 0;
int cnt = 0;
int kthLargest(TreeNode* root, int k) {
dfs(root,k);
return ans;
}
void dfs(TreeNode* root,int k){
if(root==nullptr) return ;
if(root->right) dfs(root->right,k);
cnt++;
if(cnt==k) ans=root->val;
if(root->left) dfs(root->left,k);
}
};
單函數遞歸
class Solution {
public:
int cnt = 0;
int kthLargest(TreeNode* root, int k) {
if(root == nullptr) return -1;
int ans = 0;
if(root->right) ans = kthLargest(root->right,k);
if(cnt >= k) return ans;
cnt++;
if(cnt==k) return root->val;
if(root->left) return kthLargest(root->left,k);
return -1;
}
};
迭代
class Solution {
public:
int cnt = 0;
int kthLargest(TreeNode* root, int k) {
if(root == nullptr) return -1;
int ans = 0;
if(root->right) ans = kthLargest(root->right,k);
if(cnt >= k) return ans;
cnt++;
if(cnt==k) return root->val;
if(root->left) return kthLargest(root->left,k);
return -1;
}
};
對節點加變量 int sum 表示該節點子樹大小
class Solution {
public:
int kthLargest(TreeNode* root, int k) {
if(root == nullptr) return -1;
int sum = 0;
if(root->right==nullptr) sum = 0;
else sum = root->right->sum + 1;
if(sum + 1 == k){
return root->val;
}else if(sum > k){
return kthLargest(root->right,k);
}else{
return kthLargest(root->left,k-sum);
}
}
};