LeetCode 二叉树的最近公共祖先

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

利用二叉搜索树的性质,祖先的两个孩子,左孩子的小于根节点的值,右孩子大于根节点的值。
如果根节点的值,同时大于p的值和q的值,那么在左子树找根节点;
如果根节点的值,同时小于p的值和q的值,那么在右子树找根节点。

/**
 * 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 && root->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left, p, q);
        if(root && root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right, p, q); 
        return root;
    }
};

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

两种解法

1. 递归查找

/**
 * 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 || root->val == p->val || root->val == q->val) return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if(left && right){
            return root;
        }else if(left){
            return left;
        }else if(right){
            return right;
        }
        return nullptr;
    }
};

2. 建立每个节点与父节点的映射

/**
 * 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 {
private:
    unordered_map<TreeNode*, TreeNode*> parent;
    unordered_set<TreeNode*> visited;
public:
    void traverse(TreeNode* root){
        if(!root) return;
        if(root->left){
            parent[root->left] = root;
            traverse(root->left);
        }
        if(root->right){
            parent[root->right] = root;
            traverse(root->right);
        }
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        parent[root] = nullptr;
        traverse(root);
        while(p){
            visited.insert(p);
            p = parent[p];
        }
        while(q){
            if(visited.find(q) != visited.end()){
                return q;
            }
            q = parent[q];
        }
        return nullptr;
    }
};

posted on 2022-01-31 11:12  七昂的技术之旅  阅读(10)  评论(0编辑  收藏  举报

导航