美文网首页二叉树
【剑指 offer】树中两个结点的最低公共祖先。

【剑指 offer】树中两个结点的最低公共祖先。

作者: 邓泽军_3679 | 来源:发表于2019-05-12 23:37 被阅读0次

    1、题目描述

    给出一个二叉树,输入两个树节点,求它们的最低公共祖先。

    一个树节点的祖先节点包括它本身。

    注意:
    • 输入的二叉树不为空;
    • 输入的两个节点一定不为空,且是二叉树中的节点;
    样例:

    二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]如下图所示:
      8
    /  \
    12   2
      /  \
      6   4

    1. 如果输入的树节点为2和12,则输出的最低公共祖先为树节点8。
    2. 如果输入的树节点为2和6,则输出的最低公共祖先为树节点2。

    2、问题描述:

    3、问题关键:

    4、C++代码:

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

    相关文章

      网友评论

        本文标题:【剑指 offer】树中两个结点的最低公共祖先。

        本文链接:https://www.haomeiwen.com/subject/cpxkaqtx.html