class Solution {
public:
vector<int> res;
void dfs(TreeNode *root){
if(root!=NULL){
dfs(root->left);
res.push_back(root->val);
dfs(root->right);
}
}
int getMinimumDifference(TreeNode* root) {
dfs(root);
int m=INT_MAX;
int i=0,j=1;
while(i<res.size()&&j<res.size()){
m=min(abs(res[i]-res[j]),m);
i++;j++;
}
return m;
}
};
class Solution {
public:
vector<int> res;
int count=0;//当前频率
int max_count=0;
TreeNode *pre=NULL;
void dfs(TreeNode *root){
if(root==NULL)
return;
else{
dfs(root->left);
if(pre==NULL)
{
//说明是一个元素
count++;
}
else{
//统计当前元素出现的个数
if(root->val==pre->val)
count++;
else{
count=1;
}
}
pre=root;
if(count==max_count){
res.push_back(root->val);
}
//更新max
if(count>max_count){
res.clear();
max_count=count;
res.push_back(root->val);
}
dfs(root->right);
}
}
vector<int> findMode(TreeNode* root) {
dfs(root);
return res;
}
};
思路:需要二刷 掌握思想 记录pre结点 进行中序遍历 寻找前后关系
class Solution {
public:
//使用后序遍历 回溯自底而上寻找 返回目标结点
TreeNode *dfs(TreeNode* root, TreeNode* p, TreeNode* q){
if(root==NULL||root==p||root==q){
return root;
}else{
//遍历左右子树 返回值或者为空 或者为目标结点
TreeNode *left=dfs(root->left,p,q);
TreeNode *right=dfs(root->right,p,q);
if (left != NULL && right != NULL) return root;
if (left == NULL && right != NULL) return right;
else if (left != NULL && right == NULL) return left;
else { // (left == NULL && right == NULL)
return NULL;
}
}
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
return dfs(root,p,q);
}
};
二叉树以来很难的题:
详细解释 因为要找最近公共节点 肯定是从下向上遍历 也就是回溯 而 回溯需要依据左右节点的值来进行处理 所以使用后序遍历 那我们怎末定义返回值呢? NULL肯定返回 left或者right也返回说明这个时候已经找到目标结点了 然后我们设置两个TreeNode来承载 返回值 这时候 如果 左右都不为空 就说明当前结点是目标结点返回 如果一个为空 一个不为空 说明已经找到了目标节点直接返回上一层 都为空说明没找到返回NULL 这个时候可能有第二种情况 q或者p是祖先 逻辑一样 q直接返回 因为永远是一个节点为q一个结点为空的情况 一直返回q 题目得解