普通二叉樹尋找公共祖先,二叉樹的問題基本就是遍歷,最小的公共祖先的知足下面一個性質:一、兩個節點分別在左右子樹上,二、一個節點是另外一節點的祖先spa
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 };