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

 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 {
12 public:
13     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
14     {
15         //看根节点
16         if(!root || p == root || q == root) return root;
17 
18         //1、两个结点在根节点的左子树上
19         //2、两个结点在根节点的右子树上
20         //3、两个结点在根节点的两侧
21         TreeNode* left = lowestCommonAncestor(root->left,p,q);
22         TreeNode* right = lowestCommonAncestor(root->right,p,q);
23 
24         if(!left) return right;
25         if(!right) return left;
26 
27         return root;
28     }
29 };

 

posted @ 2020-03-24 12:14  Jinxiaobo0509  阅读(135)  评论(0)    收藏  举报