• 49 二叉树的最近公共祖先



    给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

    百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 xp、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

    一共两种情况:一种是p/q是最近公共祖先,那么p和q一定在一侧,以其祖先节点往左右找一定只有left or right是有值的;另一种是除p和q以外某个点是祖先,其left和right一定是p or q,所以都不为空

    git的pull merge原理

    在这里插入图片描述
    提示:

    • 树中节点数目在范围 [ 2 , 1 0 5 ] [2, 10^5] [2,105] 内。
    • − 1 0 9 -10^9 109 <= Node.val <= 1 0 9 10^9 109
    • 所有 Node.val 互不相同 。 !!!
    • p != q
    • pq 均存在于给定的二叉树中。

    题解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 == p || root == q){
                return root;
            }
            TreeNode* left = lowestCommonAncestor(root->left, p, q);
            TreeNode* right = lowestCommonAncestor(root->right, p, q);
            if(left && right) return root;
    
            return left ? left : right;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在这里插入图片描述

    题解2 哈希表

    class Solution {
        // 每个结点值不同,所以第一个元素可以用int
        unordered_map<int, TreeNode*> fatherNodes;
        unordered_map<int, bool> visited;
    public:
    	// DFS 记录父链 
        void dfs(TreeNode* root){
            if(root->left) {
                fatherNodes[root->left->val] = root;
                dfs(root->left);
            }
            if(root->right){
                fatherNodes[root->right->val] = root;
                dfs(root->right);
            }
        }
        TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
            fatherNodes[root->val] = nullptr;
    
            dfs(root);
    		// visited
            while(p){
                visited[p->val] = true;
                p = fatherNodes[p->val];
            }
            while(q){
                if(visited[q->val]) 
                    return q;
                q = fatherNodes[q->val];
            }
    
            return nullptr;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    在这里插入图片描述

  • 相关阅读:
    C语言 指针进阶 贰
    【笔试题】【day9】
    linux(centos7)配置SSH免密登录
    CentOS挂载:解锁文件系统的力量
    [FMMPEG] parse与 demuxer
    bugku-web-社工-初步收集
    接口测试与功能测试的区别~
    嘉立创EDA专业版--PCB局部相关元件整理放置
    力扣 428. 序列化和反序列化 N 叉树 DFS
    十四、队列函数
  • 原文地址:https://blog.csdn.net/qq_43402798/article/details/133783091