面试题 04.08. 首个共同祖先

面试题 04.08. 首个共同祖先_第1张图片

面试题 04.08. 首个共同祖先_第2张图片

链接:https://leetcode-cn.com/problems/first-common-ancestor-lcci/

题解:后序遍历

/**
 *  * 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) {
        return dfs(root, p, q);
    }
    TreeNode* dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root) return nullptr;
        TreeNode* left = dfs(root->left, p, q);
        TreeNode* right = dfs(root->right, p, q);
        // root的左边和右边 都存在
        if(left && right) {
            return root;
        }
        if(root == p || root == q) {
            return root;
        }
        // 返回不为nullptr
        return left != nullptr? left:right;
    }
};

 

你可能感兴趣的:(leetcode)