Day18||530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● 236. 二叉树的最近公共祖先

530.二叉搜索树的最小绝对差

利用到二叉搜索树的中序遍历有序的性质,采用双指针方法,来比较。

class Solution {
public:
 int result=INT_MAX;
 TreeNode* pre=nullptr;
    int getMinimumDifference(TreeNode* root) {

        traversal(root);
        return result;


    }

    void traversal(TreeNode* node)
    {
        if(node==nullptr) return ;

        traversal(node->left);
        if(pre!=nullptr)
        {
            result=min(result,node->val-pre->val);
        }
        pre=node;

        traversal(node->right);
    }
};


501二叉搜索树中的众数

如果这道题是一个普通二叉树,我们就要考虑用map容器去写,但是如果是搜索二叉树的话就可以用到搜索二叉树的性质。还是用的是双指针法。但是要注意对空指针的判断和对result数组的及时清空。

class Solution {
public:
vector result;
TreeNode* pre=nullptr;
int count;
int maxcount;

    vector findMode(TreeNode* root) {
        result.clear();
        count=1;
        maxcount=1;
        pre=nullptr;
        traversal(root);
        return result;


    }
    void traversal(TreeNode *cur)
    {
        if(cur==nullptr) return ;

        traversal(cur->left);
        if(pre==nullptr)
        count=1;

       else if(pre->val==cur->val)
        count++;
        else count=1;
      

        if(count==maxcount)
        result.push_back(cur->val);

        if((count>maxcount))
        {
            maxcount=count;
            result.clear();
            result.push_back(cur->val);
        }

          pre=cur;

     traversal((cur->right));


    }
};

236. 二叉树的最近公共祖先

这道题还是很有难度的。其实要考虑清楚两种情况,第一种情况是q不在q的路径上,另外一种是在,但是实际上我们的逻辑已经包含对这种情况的判断,否则还要单独去写。后序的从下向上,考虑清楚递归逻辑还是很重要的。

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

        if(root==NULL) return NULL;
        if(root==p||root==q) return root;

        TreeNode* left=NULL;
        TreeNode* right=NULL;

        left=lowestCommonAncestor(root->left,p,q);
        right=lowestCommonAncestor(root->right,p,q);

        if(left!=NULL&&right!=NULL)
        return root;
        
        if(left==NULL&&right!=NULL) return right;
        if(left!=NULL&right==NULL) return left;

        return NULL;

    }
};

你可能感兴趣的:(算法,数据结构,c++,leetcode)