236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Given the following binary tree: root = [3,5,1,6,2,0,8,null,null,7,4]
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Note:
All of the nodes' values will be unique.
p and q are different and both values will exist in the binary tree.
題意:給定一個二叉樹, 找到該樹中兩個指定節(jié)點的最近公共祖先鹦蠕。
思路:
如果以root為根的子樹中包含p和q姥饰,則返回它們的最近公共祖先
如果只包含p,則返回p
如果只包含q,則返回q
如果都不包含缓熟,則返回NULL
右子樹情況:
1.右邊也都不包含,則right=NULL,最終需要返回NULL
2.右邊只包含p或q僻孝,則right=p或者q,最終需要返回p或q
3.右邊同時包含p和q守谓,則right是最近公共祖先穿铆,我們最終也需要返回最近公共祖先
/**
* 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) {
if(root==NULL||root==p||root==q)
return root;
TreeNode *left=lowestCommonAncestor(root->left,p,q);
TreeNode *right=lowestCommonAncestor(root->right,p,q);
if(left!=NULL&&right!=NULL)
return root;//如果p,q剛好在左右兩個子樹上
if(left==NULL)
return right;//僅在右子樹
if(right==NULL)
return left;//僅在左子樹
return root;
}
};