530. 二叉搜索树的最小绝对差
class Solution {
public:
int min_diff=INT_MAX, last=-1;
void inorder(TreeNode* root){
if(root==nullptr)
return;
inorder(root->left);
if(last!=-1){
min_diff=min(min_diff,abs(root->val-last));
}
last=root->val;
inorder(root->right);
}
int getMinimumDifference(TreeNode* root) {
inorder(root);
return min_diff;
}
};
501. 二叉搜索树中的众数
class Solution {
public:
int max_freq = INT_MIN, cnt;
TreeNode* pre = nullptr;
vector<int> res;
void inorder(TreeNode* root) {
if (root == nullptr)
return;
inorder(root->left);
if (pre) {
if (root->val == pre->val)
cnt++;
else
cnt = 1;
}
else
cnt = 1;
if (cnt > max_freq) {
max_freq = cnt;
res.clear();
res.push_back(root->val);
}
else if (cnt == max_freq)
res.push_back(root->val);
pre = root;
inorder(root->right);
}
vector<int> findMode(TreeNode* root) {
inorder(root);
return res;
}
};
利用搜索树的中序递增特性,直接统计不同节点频率,并构造输出。不使用额外的循环和空间。
236. 二叉树的最近公共祖先
class Solution {
public:
bool dfs(TreeNode* root, TreeNode* target, vector<TreeNode*>& path){
if(root==nullptr)
return false;
path.push_back(root);
if(root==target)
return true;
if(dfs(root->left,target,path)|| dfs(root->right,target,path))
return true;
path.pop_back();
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode *res;
vector<TreeNode*> path1,path2;
dfs(root,p,path1);
dfs(root,q,path2);
for(int i=0; i<path1.size()&&i<path2.size();i++){
if(path1[i]==path2[i])
res=path1[i];
}
return res;
}
};
只需搜索一条路径,所以设置返回值bool,用来提前终止回溯。对于树的问题,回溯的下一层就是递归搜索root->left及root->right。