Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given the following binary tree:  root = [3,5,1,6,2,0,8,null,null,7,4]

 

Example 1:

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
/* 找出p q最邻近祖先
 * 用vector<> 记录path 递归进入时计入 返回时删除
 * 从头遍历两个path 输出最后一次相同的节点
 *
 * */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(!root || !p || !q)   return NULL;
        vector<TreeNode*> pathP, pathQ;
        bool foundP=false, foundQ= false;
        dfs(root, pathP, p, foundP);
        dfs(root, pathQ, q, foundQ);

        TreeNode *ret=root;
        for(int i=0;i<min(pathP.size(), pathQ.size());i++){
            if(pathP[i] == pathQ[i])    ret = pathP[i];
            else break;
        }
        return ret;

    }
    void dfs(TreeNode* root, vector<TreeNode*> &path, TreeNode *tar, bool &found){
        if(root == tar){
            found = true;
            return;
        }
        if(!found && root->left){
            path.push_back(root->left);
            dfs(root->left, path, tar, found);
            if(!found) path.pop_back();  // 非常重要 不然在找到之后再递归返回时会pop出父节点
        }
        if(!found && root->right){
            path.push_back(root->right);
            dfs(root->right, path, tar, found);
            if(!found) path.pop_back();
        }
    }
};

递归的解决方法:

/* 找出p q最邻近祖先
 * 递归想法:  首先这个函数是求以root为根节点的p和q的LCA(lowest common ancester)
 * root = p 或者 root=q 是一种边界条件 (递归到了这个节点) 还有一种root=NULL eg: 起始pq都在root左分支上
 * 对右分支递归的结果返回NULL
 *
 * 递归情况:
 * 1.  p,q 在 左右 分支上
 * 2.  p,q 都在左分支上 右分支返回NULL
 * 3.  p,q 都在右分支上 左分支返回NULL
 * */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
           if(!root || root==p || root==q)  return root;

           auto left = lowestCommonAncestor(root->left, p, q);
           auto right = lowestCommonAncestor(root->right, p, q);
           if(!left)    return right;
           else if(!right)  return left;
           else return root;    // left!=NULL && right!=NULL
    }

};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值