leetcode-236-二叉樹公共祖先
阿新 • • 發佈:2020-07-28
思路:
公共祖先需要分為三種情況:
1.pq包含在root的左右子樹中,則root就是他們公共祖先
2.pq包含在root的右子樹中,則公共祖先是右子樹
3.pq包含在root的左子樹中,則公共祖先在左子樹
程式碼:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * };*/ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { //如果root為根的子樹中包含p和q,則返回他們的最近的公共祖先 //如果只包含P,則返回q //如果只包含q,則放回q //如果都不包含,則返回null if(!root || root==p || root==q) return root; auto left=lowestCommonAncestor(root->left,p,q); auto right=lowestCommonAncestor(root->right,p,q); if(!left) return right; //若left不包含pq,則直接返回right if(!right) return left;//若right不包含pq,則直接返回left return root; //若right and left 都不為空,證明左右各一個,所以root就是公共祖先 } };