Interview question 04.08. The first common ancestor

Interview question 04.08. The first common ancestor

Idea: either one left and one right, return to root, or return left, or return right

/**
 * 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==NULL || 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;
    }
};

 

Published 248 original articles · Like 29 · Visits 30,000+

Guess you like

Origin blog.csdn.net/weixin_38603360/article/details/105456181