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

LeetCode OJ:Lowest Common Ancestor of a Binary Tree(最近公共祖先)

时间:2015-10-07 22:54:40      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

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.

找最近的公共祖先,仔细想一想,其实l与r的最小的公共祖先c满足一定条件,那就是l以及r一定在c的左右分支上,不可能都是左或右分支的。否则一定就不是最近的公共祖先,

代码如下,用递归写出来还是比较简单易懂的。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13         if (root == NULL) return  NULL; //无其他节点,直接返回
14         if (root == p || root == q) return root; 
15         TreeNode * leftNode = lowestCommonAncestor(root->left, p, q);
16         TreeNode * rightNode = lowestCommonAncestor(root->right, p, q);
17         if (leftNode && rightNode) return root;  //找到LCA,返回LCA
18         return leftNode ? leftNode : rightNode;  
19     }
20 };

还有一种方法是遍历tree,然后找出到达p以及q分别的路径,找到路径之后,遍历两条路径,出现分叉的第一个点就是p与q的LCA。具体代码先不贴了  比较麻烦。

LeetCode OJ:Lowest Common Ancestor of a Binary Tree(最近公共祖先)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4859653.html

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