标签:
普通二叉树寻找公共祖先,二叉树的问题基本就是遍历,最小的公共祖先的满足下面一个性质: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