首页 > 其他 > 详细

面试题 04.08. 二叉树的最近公共祖先

时间:2020-05-10 00:22:26      阅读:74      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

解答:

技术分享图片

 

 

 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     {
14         if(root == NULL)
15         {
16            return NULL;
17         }
18         if(root == p || root == q)
19         { 
20             return root;
21         }
22             
23         TreeNode* left =  lowestCommonAncestor(root->left, p, q);
24         TreeNode* right = lowestCommonAncestor(root->right, p, q);
25        
26         if(left == NULL)
27             return right;
28         if(right == NULL)
29             return left;      
30         if(left && right) // p和q在两侧
31             return root;
32         
33         return NULL; // 必须有返回值      
34     }
35 };

 

------------恢复内容开始------------

题目:

技术分享图片

 

 

解答:

 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     {
14         if(root == NULL)
15         {
16            return NULL;
17         }
18         if(root == p || root == q)
19         { 
20             return root;
21         }
22             
23         TreeNode* left =  lowestCommonAncestor(root->left, p, q);
24         TreeNode* right = lowestCommonAncestor(root->right, p, q);
25        
26         if(left == NULL)
27             return right;
28         if(right == NULL)
29             return left;      
30         if(left && right) // p和q在两侧
31             return root;
32         
33         return NULL; // 必须有返回值      
34     }
35 };

 

------------恢复内容结束------------

面试题 04.08. 二叉树的最近公共祖先

原文:https://www.cnblogs.com/ocpc/p/12861131.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!