码迷,mamicode.com
首页 > 其他好文 > 详细

88 Lowest Common Ancestor of a Binary Tree

时间:2018-07-15 22:18:37      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:顶点   lin   tail   左右   最近公共祖先   htm   font   rap   view   

原题网址:https://www.lintcode.com/problem/lowest-common-ancestor-of-a-binary-tree/description

描述

给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。

最近公共祖先是两个节点的公共的祖先节点且具有最大深度。

假设给出的两个节点都在树中存在

您在真实的面试中是否遇到过这个题?  

样例

对于下面这棵二叉树

  4
 / 3   7
   /   5   6

LCA(3, 5) = 4

LCA(5, 6) = 7

LCA(6, 7) = 7

标签
二叉树
LintCode 版权所有
 
 
思路:碰到二叉树问题基本上递归。这道题在递去过程中寻找A、B节点,一旦找到停止递归,进行回溯,回溯过程中找到最近公共父节点。
1.递去时,若找到A或者B,当即返回该节点,否则返回NULL。
2.递归式,在左右子树中分别寻找。
3.回溯时,
若A、B在当前根节点左右两侧,那么当前根节点就是A、B的LCA,返回当前根节点;
若A,B在当前根节点的同一侧(left或right),那么另一侧的寻找结果为NULL。寻找结果不为NULL的那侧返回的节点,也就是最先找到的节点,即为A、B的LCA。
 
 
 
AC代码:
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param root: The root of the binary search tree.
     * @param A: A TreeNode in a Binary.
     * @param B: A TreeNode in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
    TreeNode * lowestCommonAncestor(TreeNode * root, TreeNode * A, TreeNode * B) {
        // write your code here
    if (root==NULL||A==root||B==root)
    {
        return root;
    }
    TreeNode * left=lowestCommonAncestor(root->left,A,B);
    TreeNode * right=lowestCommonAncestor(root->right,A,B);
    if (left&&right)
    {
        return root;
    }
    else if (left)
    {
        return left;
    }
    else if(right)
    {
        return right;
    }
    else
    {
        return NULL;
    }
    
    }
};

 

参考:
Lowest Common Ancestor  讲解详细,还提供了另外一种计数器的方法
LintCode-最近公共祖先  用DFS求出顶点到A和B的路径,再从两条路径中找到第一个不相等的节点,则上一个节点即为LCA。
 
[LeetCode] Lowest Common Ancestor of a Binary Tree系列   总结了系列问题,普通二叉树LCA和二叉搜索树的LCA
 
 

88 Lowest Common Ancestor of a Binary Tree

标签:顶点   lin   tail   左右   最近公共祖先   htm   font   rap   view   

原文地址:https://www.cnblogs.com/Tang-tangt/p/9314921.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!