您的位置:首页 > 其它

Lowest Common Ancestor of a Binary Tree

2015-11-21 22:38 274 查看
题目描述:

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

_______3______
/              \
___5__          ___1__
/      \        /      \
6      _2       0       8
/  \
7   4

For example, the lowest common ancestor (LCA) of nodes
5
and
1
is
3
. Another example is LCA of nodes
5
and
4
is
5
, since a node can be a descendant of itself according to the LCA definition.

题目分析:

首先,题目给出的是一个二叉树,同时给定两个节点,要求寻找两个节点的最低公共祖先(可以为两节点)。也就是说目标节点的左右子树分别包含两个节点,或者是节点本身。

解题思路:

节点a与节点b的公共祖先c一定满足:a与b分别出现在c的左右子树上(如果a或者b本身不是祖先的话)。首先想到的是递归孙发,分别在根节点的左子树和右子树进行寻找,找到两节点,返回当前节点,没有找到则返回空。若根节点的左右子树找到了两节点,该节点就是所找的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 == NULL) return NULL;
if (root == p || root == q) return root;
TreeNode *L = lowestCommonAncestor(root->left, p, q);
TreeNode *R = lowestCommonAncestor(root->right, p, q);
if (L && R) return root;
return L ? L : R;
}
};


为了让读者更容易明白此算法,下面举个例子进行分析:

寻找6,4的LCA



第一步:

根节点3,不是所找节点,进入3的左右子树5,1寻找。



第二步:

根节点5,不是所找节点,进入5的左右节点6,2寻找;

根节点1,不是所找节点,进入1的左右节点0,8寻找。



第三步:

根节点6,是所找节点,返回此节点;

根节点2,不是所找节点,进入2的左右节点7,4寻找;

根节点0,8,不是所找节点,返回NULL。



第四步:

根节点7,不是所找节点,返回NULL。

根节点4,是所找节点,返回此节点;



第五步:

返回L = 6,R= 2,返回root = 5,找到结果。





分析一下此算法的复杂度,最坏的情况,也就是每个节点都需要进行检查,时间复杂大为O(n),空间复杂的为O(1)。

递归算法优点是思路很清晰,代码非常简洁,缺点是,在寻找的两个节点处于较深的位置时,需要多次压栈迭代,算法复杂度较高。

此博客中的内容均为原创或来自网络,不用做任何商业用途。欢迎与我交流学习,我的邮箱是lsa0924@163.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: