二叉树的两个节点的最近公共祖先leetcode

从根节点开始遍历,如果p和q中的任意一个和root匹配,则root就是最低公共选,如果不匹配,分别左右递归左右子树,如果有一个节点出现在左子树,另外一个出现在右子树,则root就是最低公共祖先,如果节点都出现在左子树,则最低公共祖先出现在左子树,否则在右子树

/**
 * 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!=NULL&&right!=NULL) return root;
        return left==NULL?right:left;
    }
};

猜你喜欢

转载自blog.csdn.net/u010589524/article/details/82895338