两个面试案例
剑指 Offer 67. 把字符串转换成整数
题目
代码
class Solution {
public:
int strToInt(string str) {
int l = 0;
int len = str.size();
//字符串为空
if(len == 0) {
return 0;
}
//去除空格
while(l < len && str[l] == ' ') {
l++;
}
int res = 0;
int sign = 1;
if(l < len && (str[l] == '+' || str[l] == '-')) {
if(str[l] == '-') {
sign = -1;
}
l++;
}
while(l < len && isdigit(str[l])) {
//通过边界值判断是否超过范围
if(sign == 1 && res > (INT_MAX - (str[l] - '0')) / 10) return INT_MAX;
if(sign == -1 && res < (INT_MIN + (str[l] - '0')) / 10) {
return INT_MIN;
}
res = res * 10 + (str[l] - '0') * sign;
l++;
}
return res;
}
};
剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
题目
代码
由于是二叉搜索树,利用大小关系即可判断。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr) {
return nullptr;
}
if(p->val > q->val) {
//首选确定p与q的大小
return lowestCommonAncestor(root, q, p);
}
//p和q分别在root的左右子树
if(root->val >= p->val && root->val <= q->val) {
return root;
}
//如果都在左子树
if(root->val > q->val) {
return lowestCommonAncestor(root->left, p, q);
//如果都在右子树
}else {
return lowestCommonAncestor(root->right, p, q);
}
}
};
剑指 Offer 68 - II. 二叉树的最近公共祖先
题目
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//确定递归函数的返回值
//如果当前节点的左子树和右子树都是p和q的公共节点,那么当前节点即为最近公共祖先,返回该节点
//如果左子树和右子树都不是,那么返回nullptr
//如果一个是,一个不是,就返回是的这个节点
//base case
if(root == nullptr) {
return nullptr;
}
if(root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
//左子树和右子树都是p和q的祖先
if(left != nullptr && right != nullptr) {
return root;
//只有左子树是p的祖先
}else if(left != nullptr) {
return left;
只有右子树是p的祖先
}else if(right != nullptr) {
return right;
}
return nullptr;
}
};