题目:
解答:
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 };
------------恢复内容结束------------
原文:https://www.cnblogs.com/ocpc/p/12861131.html