剑指 Offer 54. 二叉搜索树的第k大节点

tech2025-02-02  3

剑指 Offer 54. 二叉搜索树的第k大节点 - 力扣(LeetCode)

简单写法: 中序遍历就可以了

class Solution { public: vector<int> a; void inorder(TreeNode* root){ if(!root) return; inorder(root->left); a.push_back(root->val); inorder(root->right); } int kthLargest(TreeNode* root, int k) { inorder(root); return a[a.size()-k]; } };

数组其实没必要使用,优化一下,根据二叉搜索树的性质,右子树肯定更大,所以dfs先遍历右边再考虑左边就行,设置一个计数变量,达到k的时候就退出来。

class Solution { public: int k = 0, cnt = 0; int res = 0; void dfs(TreeNode* root){ if(!root) return; dfs(root->right); ++cnt; if(cnt == k){ res = root->val; return; } dfs(root->left); } int kthLargest(TreeNode* root, int k) { this->k = k; dfs(root); return res; } };

两个遍历就可以了:

class Solution { public: int k = 0, res = 0; void dfs(TreeNode* root){ if(!root) return; dfs(root->right); if(--k == 0){ res = root->val; return; } dfs(root->left); } int kthLargest(TreeNode* root, int k) { this->k = k; dfs(root); return res; } };
最新回复(0)