1. 程式人生 > >一般二叉樹求最近公共祖先(最簡單的程式碼)

一般二叉樹求最近公共祖先(最簡單的程式碼)

當遍歷到一個root點的時候,

1.判斷root是不是null如果root為null,那麼就無所謂祖先節點,直接返回null就好了

2.如果root的左子樹存在p,右子樹存在q,那麼root肯定就是最近祖先

3.如果pq都在root的左子樹,那麼就需要遞迴root的左子樹,右子樹同理

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
 2     if(root == NULL || root == p || root ==q) return root;
 3     TreeNode* left
= lowestCommonAncestor(root->left, p, q); 4 TreeNode* right = lowestCommonAncestor(root->right, p, q); 5 if(left && right){ 6 return root; 7 }else{ 8 return left == NULL ? right : left; 9 } 10 }