【LeetCode-236 | 二叉树的最近公共祖先】_#include

【LeetCode-236 | 二叉树的最近公共祖先】_子树_02

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>

using namespace std;


struct TreeNode{
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(): val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right): val(x), left(left), right(right) {}
};


class Solution {
public:
    /*
        利用后序遍历进行遍历整棵树:如果找到一个节点,发现左子树出现节点p、右子树出现节点q,或左子树出现节点q、右子树出现节点p,那么该节点就是节点p和q的最近公共祖先。
    */
    // 1.确定递归函数入参及返回值
    // 返回值表示是否找到了节点p或节点q,同时返回最近公共祖先节点。因此,函数返回值类型为TreeNode*,如果遇到p或者q,就把q或者p返回,返回值不为空,就说明找到了q或者p。
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        // 2.确定递归函数的终止条件    
        if(root == p || root == q || root == nullptr) return root;
        // 3.确定单层递归逻辑
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);

        if(left != nullptr && right != nullptr) return root;
        if(left == nullptr && right != nullptr) return right;
        if(left != nullptr && right == nullptr) return left;
        else return nullptr;
    }
};