1.same tree
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
if(p == NULL && q == NULL)
return true;
else if(p == NULL || q == NULL)
return false;
if(p->val != q->val)
return false;
else
return (isSameTree(p->left,q->left))&&(isSameTree(p->right,q->right));
}
};
2. depth in the tree
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
if(root == NULL)
return 0;
return 1 + max(maxDepth(root->left),maxDepth(root->right));
}
};
4. reverse integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
其次,给的答案是对于尾部是0,不予表示的,
越界也就越界了没有处理
class Solution {
public:
int reverse(int x) {
int r = 0;
while(x != 0)
{
r = r * 10 + x % 10;
x = x / 10;
}
return r;
}
};
这个溢出处理等于没有什么特别的处理啊。
int reverse(int x)
{
int r = 0;
const int max = 0x7fffffff; //int最大值
const int min = 0x80000000; //int最小值
while(x != 0)
{
r = r * 10 + x % 10;
if (r > max || r < min) //溢出处理
{
r = r > 0 ? max : min;
return r;
}
x =x /10;
}
return r;
}