236-二叉树的最近公共祖先

函数功能:

1、如果p q都存在,返回他们的公共祖先

2、只存在一个,那就返回存在的一个

3、都不存在,返回NULL

递归左右子树,左子树的结果为left1,右子树结果为right1

left1空代表结果(公共祖先)在right1,反之亦然。

如果都非空,说明p q在左右两边,此时要返回根结点。

否则就是都空的情况,返回NULL

 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)
14         {
15             return NULL;
16         }
17         if(root==p||root==q)
18         {
19             return root;
20         }
21         TreeNode* left1=lowestCommonAncestor(root->left,p,q);
22         TreeNode* right1=lowestCommonAncestor(root->right,p,q);
23         if(left1==NULL)
24         {
25             return right1;
26         }
27         if(right1==NULL)
28         {
29             return left1;
30         }
31         if(left1&&right1)
32         {
33             return root;
34         }
35         return NULL;
36 
37         
38     }
39 };
View Code

总结:这个题和前面的235题进行对比,就是二叉树和二叉搜索树概念的区别,很好理解,代码都是统一的模板格式,建议背诵下来,解题就方便了很多。

猜你喜欢

转载自www.cnblogs.com/nxnslc-blog/p/12400604.html