【LeetCode 236】Lowest Common Ancestor of a Binary Tree

题目描述:

给一棵二叉树的根节点,找出两个节点的最近公共祖先。

思路:

递归在左右子树查找,如果当前根节点为空或与其中任一节点相同,返回。如果两边都找到非空节点,LCA为左右子树的根节点,否则返回非空节点。

代码:

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

好多天不刷题了。

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/90209774