二叉树力扣刷题(17)

47 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情

剑指 Offer 68 - II. 二叉树的最近公共祖先

思路:

代码:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == nullptr || root == p || root == q) return root;
        TreeNode *left = lowestCommonAncestor(root->left, p, q);
        TreeNode *right = lowestCommonAncestor(root->right, p, q);
        if(left == nullptr) return right;
        if(right == nullptr) return left;
        return root;
    }
};

剑指 Offer 68 - I. 二叉搜索树的最近公共祖先

思路:

代码:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left, p, q);
        if (root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right, p, q);
        return root;
    }
};

104. 二叉树的最大深度

思路:

代码:

class Solution {
public:
    int ans = 0;
    void maxc(TreeNode*root, int deep) {
        if (root == NULL) return ;
        ans = max(ans, deep);
        maxc(root->left, deep + 1);
        maxc(root->right, deep + 1);
    }
    int maxDepth(TreeNode* root) {
        maxc(root, 1);
        return ans;
    }
};

剑指 Offer 55 - I. 二叉树的深度

思路:

代码:

class Solution {
public:
    int ans = 0;
    void maxc(TreeNode*root, int deep) {
        if (root == NULL) return ;
        ans = max(ans, deep);
        maxc(root->left, deep + 1);
        maxc(root->right, deep + 1);
    }
    int maxDepth(TreeNode* root) {
        maxc(root, 1);
        return ans;
    }
};

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

思路:

代码:

class Solution {
public:
    int count,p;
    void res(TreeNode*root) {
        if (root == NULL) return;
        res(root->right);
        count -= 1;
        if (count == 0) {
            p = root->val;
            return;
        }
        res(root->left);
    }
    int kthLargest(TreeNode* root, int k) {
        count = k;
        res(root);
        return p;
    }
};

剑指 Offer 34. 二叉树中和为某一值的路径

思路:

代码:

class Solution {
public:
    vector<vector<int>>ret;
    vector<int> res;
    void pathsum(TreeNode*root, int target) {
        if (!root) return;
        res.push_back(root->val);
         target -= root->val;
        if ((root->left == nullptr && root->right == nullptr) && target == 0 ) {
            ret.push_back(res);
        }
        
       
       
        cout<<target;
        pathSum(root->left, target);
        pathSum(root->right, target);
        res.pop_back();
    }

    vector<vector<int>> pathSum(TreeNode* root, int target) {
        if (root == nullptr) return ret;
        pathsum(root, target);
        return ret;
    }
};