day19
1.剑指 Offer 64. 求 1 + 2 + … + n
1 class Solution { 2 public: 3 int sumNums(int n) { 4 n > 1 && (n += sumNums(n - 1)); 5 return n; 6 } 7 };
2.剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
因为是二叉搜索树,所以根据其性质可分为三种情况(使p < q):
i.p、q一个在左子树一个在右子树,或者 其中一个等于root,公共祖先就会是root
ii.q的值小于root,公共祖先会在左子树
iii.p的值大于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(p -> val > q -> val) return lowestCommonAncestor(root,q,p); 14 if(p -> val == root -> val || q -> val == root -> val || (root -> val > p -> val && root -> val < q -> val)) return root; 15 if(q -> val < root -> val) return lowestCommonAncestor(root -> left,p,q); 16 /*else if(p -> val > root -> val)*/ 17 return lowestCommonAncestor(root -> right,p,q); 18 } 19 };
3.剑指 Offer 68 - II. 二叉树的最近公共祖先
思路与二叉搜索树那里一样,只是二叉搜索树可根据其左右节点值大小直接判断p、q是否在左右子树,而此题要遍历其左右子树才可判断(find函数)
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 -> val == p -> val || root -> val == q -> val ) 14 return root; 15 if(find(root -> left,p -> val) && find(root -> left,q -> val)) 16 return lowestCommonAncestor(root -> left,p,q); 17 else if(find(root -> right,p -> val) && find(root -> right,q -> val)) 18 return lowestCommonAncestor(root -> right,p,q); 19 return root;//剩下一种情况就是p、q分别在左右子树上 20 } 21 22 bool find(TreeNode* root,int val){ 23 if(root == nullptr) return false; 24 if(root -> val == val) return true; 25 if(find(root -> left,val) || find(root -> right,val)) return true; 26 return false; 27 } 28 };
理解 lowestCommonAncestor函数返回的是最近公共祖先
left不为空说明左子树存在最近公共祖先,right同理
4种情况:i.left != nullptr && right != nullptr,说明p、q一个在左子树一个在右子树,即最近公共祖先为root
ii.left == nullptr && right == nullptr,说明 rootroot 的左右子树中都不包含 p,q ,返回空
iii.left != nullptr && right == nullptr,说明p、q最近公共祖先在左子树,返回left
iv.left == nullptr && right != nullptr,说明p、q最近公共祖先在右子树,返回right
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 == nullptr || root == p || root == q) return root;//这里,root为空的话返回的也是nullptr 14 TreeNode* left = lowestCommonAncestor(root -> left,p,q); 15 TreeNode* right = lowestCommonAncestor(root -> right,p,q); 16 if(left != nullptr && right != nullptr) return root; 17 if(left == nullptr && right == nullptr) return nullptr; 18 if(left) return left; 19 /* if(right) */ 20 return right; 21 } 22 };

浙公网安备 33010602011771号