《从头再来》剑指offer.68II 二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

特判不为空过后,一定要马上判断root是否等于p或q,如果等则直接返回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 == nullptr) return nullptr;
        //少判断了当前节点就是需要的节点!!!!
        if(root == p || root == q)  return root;

        //取得左、右子树
        TreeNode* leftTree = lowestCommonAncestor(root->left, p, q);
        TreeNode* rightTree = lowestCommonAncestor(root->right, p, q);

        if(leftTree && rightTree)   return root;
        else if(leftTree && !rightTree) return leftTree;
        else if(!leftTree && rightTree) return rightTree;
        else if(!leftTree && !rightTree)    return nullptr;


        return root;//最后为什么要return root?
    }
};

 

posted @ 2021-06-08 22:08  丶原来是枝知啊i  阅读(49)  评论(0)    收藏  举报