二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4]

 

 

示例 1:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
示例 2:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
 

说明:

所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中。

 

比较麻烦的做法
思路:把p的父结点、祖父结点、祖祖父...直到root找出来,放到set中,再把q的父结点找出来看有没有在set中,若有则返回该父结点,若无则再找父结点的父结点看有没有在set中,循环直到root.
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13         if(root==NULL||p==NULL||q==NULL) return NULL;
14         if(p==q)return p;
15         if(p==root||q==root)return root;
16         TreeNode* pParent=p;
17         TreeNode* qParent=q;
18         set<TreeNode*> SetP;
19 
20         SetP.insert(pParent);
21         while(pParent!=root)
22         {
23             pParent=findParent(root,pParent);
24             SetP.insert(pParent);
25         }
26         while(qParent!=root)
27         {
28             if(SetP.find(qParent)!=SetP.end())
29                 return qParent;
30             qParent=findParent(root,qParent);
31         }    
32         return qParent;
33     }
34     TreeNode* findParent(TreeNode* root,TreeNode* e)//找出父结点
35     {
36         if(root==NULL||root==e) return root;
37         if(root->left==e||root->right==e) return root;
38         TreeNode* left=findParent(root->left,e);
39         TreeNode* right=findParent(root->right,e);
40         if(left==NULL) return right;
41         if(right==NULL) return left;
42         return NULL;   
43     }
44 };

 

更简单的做法:

在root的左子树和右子树同时找p和q,若p和q分别分布在root的左右子树,则root为所求
若左子树返回NULL,则说明p和q都在右子树,则进入右子树执行1.
若右子树返回NULL,则说明p和q都在左子树,则进入左子树执行1

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13         if(root==NULL||p==root||q==root) return root;
14         TreeNode* left=lowestCommonAncestor(root->left,p,q);
15         TreeNode* right=lowestCommonAncestor(root->right,p,q);
16         if(!left) return right;
17         if(!right) return left;
18         return root;
19     }
20 };

 

posted @ 2020-04-28 20:33  江雨牧  阅读(379)  评论(0)    收藏  举报