二叉树最近公共父节点

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* findFisrtCommonParent(TreeNode* root, TreeNode* n1, TreeNode* n2){
    if(!root || root == n1 || root == n2) {
        return root;
    }
    TreeNode* ret1 = findFisrtCommonParent(root->left, n1, n2);
    TreeNode* ret2 = findFisrtCommonParent(root->right, n1, n2);
    if(ret1 && ret2) return root;
    if (ret1) return ret1;
    if (ret2) return ret2;
    return nullptr;
}

类似问题:
https://www.cnblogs.com/kaituorensheng/p/3960263.html

你可能感兴趣的:(二叉树最近公共父节点)