0
点赞
收藏
分享

微信扫一扫

【C++二叉树中两节点的最近公共祖先】

萨科潘 2022-04-25 阅读 43
c++

题目要求:

给出二叉树的头结点和树上的两个节点,返回这两个节点最近的公共节点

思路:

递归套路:左树上返回需要的信息,右树上返回需要的信息,然后再根据头结点的信息返回当前节点的信息(类似于后序遍历的返回方式)


代码

参考左神代码编写

#include <iostream>
using namespace std;
struct Node
{
    int value;
    Node *left;
    Node *right;
    Node() : value(0), left(nullptr), right(nullptr) {}
    Node(int x) : value(x), left(nullptr), right(nullptr) {}
    Node(int x, Node *left, Node *right) : value(x), left(left), right(right) {}
};

Node *lowest_ancestor(Node *head, Node *nod1, Node *nod2)
{
    if (head == nullptr || head == nod1 || head == nod2)
    {
        return head;
    }
    Node *lft = lowest_ancestor(head->left, nod1, nod2);
    Node *rght = lowest_ancestor(head->right, nod1, nod2);
    if (lft != nullptr && rght != nullptr)
    {
        return head;
    }
    return lft != nullptr ? lft : rght;
}

int main()
{
    /*
                a(1)
              /      \
            b(2)      c(3)
          /      \
        d(4)     e(5)
    */

    Node e(5);
    Node d(4);
    Node c(3);
    Node b(2, &d, &e);
    Node a(1, &b, &c);

    Node *low_ancest = lowest_ancestor(&a, &e, &c);
    cout << "最近公共祖先为:" << endl
         << low_ancest->value << endl;
    return 0;
}

举报

相关推荐

0 条评论