树06

501. 二叉搜索树中的众数

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> result;
    int count = 1;
    int m = 0;
    TreeNode* pre = nullptr;
    void travesal(TreeNode *cur)
    {
        if (cur == nullptr) return;
        travesal(cur -> left);
        if (pre != nullptr)
        {
            if (pre -> val == cur -> val)
            {
                count++;
            }
            else
            {
                count = 1;
            }
        }
        pre = cur;
        if (count == m){
            result.push_back(cur -> val);
        }
        if (count > m)
        {
            m = count;
            result.clear();
            result.push_back(cur -> val);
        }
        travesal(cur -> right);
    }

    vector<int> findMode(TreeNode* root) {

        travesal(root);
        return result;

    }
};

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == NULL) return root;
        if (root == p || root == q) return root;
        TreeNode* left = lowestCommonAncestor(root -> left, p, q);
        TreeNode* right = lowestCommonAncestor(root -> right, p, q);
        if (left != NULL && right != NULL) return root;
        else if (left == NULL && right != NULL) return right;
        else if (right == NULL && left != NULL) return left;
        else
        {
            return NULL;
        }
    }
};

235. 二叉搜索树的最近公共祖先

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == NULL) return root;

        if (root -> val > p -> val && root -> val > q -> val){
            TreeNode* left = lowestCommonAncestor(root -> left, p, q);
            if (left != NULL) return left;
        }
        else if (root -> val < p -> val && root -> val < q -> val){
            TreeNode* right = lowestCommonAncestor(root -> right, p, q);
            if (right != NULL) return right;
        }
       
        return root;

    }
};
posted @ 2025-08-02 11:42  skyler886  阅读(5)  评论(0)    收藏  举报