首页 > 其他 > 详细

Lowest Common Ancestor of a Binary Tree

时间:2015-08-21 15:07:47      阅读:118      评论:0      收藏:0      [点我收藏+]

普通二叉树寻找公共祖先,二叉树的问题基本就是遍历,最小的公共祖先的满足下面一个性质:1、两个节点分别在左右子树上,2、一个节点是另一节点的祖先

 1 class Solution {
 2 public:
 3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
 4         TreeNode* pr,*qr;
 5         if(root==NULL)
 6             return NULL;
 7         cout<<root->val<<endl;
 8         if(p==root||q==root)
 9             return root;
10         pr=lowestCommonAncestor(root->left,p,q);
11         qr=lowestCommonAncestor(root->right,p,q);
12         if(pr!=NULL&&qr!=NULL)
13            return root;
14         if(pr!=NULL)
15             return pr;
16         else
17             return qr;
18     }
19 };

 

Lowest Common Ancestor of a Binary Tree

原文:http://www.cnblogs.com/ZhangYushuang/p/4747764.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!