面试题27:二叉树的镜像
class Solution {
public:
TreeNode* mirrorTree(TreeNode* root) {
if(root != NULL){
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
mirrorTree(root->left);
mirrorTree(root->right);
}
return root;
}
};
面试题28:对称的二叉树
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL)
return true;
return helper(root->left, root->right);
}
bool helper(TreeNode* lp, TreeNode* rp){
if(lp == NULL && rp == NULL)
return true;
if(lp == NULL || rp == NULL)
return false;
if(lp->val == rp->val)
return helper(lp->left, rp->right) && helper(lp->right, rp->left);
return false;
}
};
面试题29:顺时针打印数组
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
int n = matrix.size();
if(n == 0)
return ans;
int m = matrix[0].size();
vector<vector<int> > mark(n, vector<int>(m, 0));
int i = 0, j = 0, cnt = 0;
ans.push_back(matrix[0][0]);
mark[0][0] = 1;
while(ans.size() < m*n){
\\ 先向右再向下再向左最后向上
while(j+1 < m && mark[i][j+1] == 0){
j += 1;
mark[i][j] = 1;
ans.push_back(matrix[i][j]);
}
while(i+1 < n && mark[i+1][j] == 0){
i += 1;
mark[i][j] = 1;
ans.push_back(matrix[i][j]);
}
while(j-1 >= 0 && mark[i][j-1] == 0){
j -= 1;
mark[i][j] = 1;
ans.push_back(matrix[i][j]);
}
while(i-1 >= 0 && mark[i-1][j] == 0){
i -= 1;
mark[i][j] = 1;
ans.push_back(matrix[i][j]);
}
}
return ans;
}
};