Symmetric Tree:
//一开始用了中序遍历树,检查输出数组是否对称的方法,上传代码后juage错误。
class Solution {
public:
vector<int> temp;
bool isSymmetric(TreeNode* root) {
if (root == NULL)
return true;
middle_order(root);
auto _1_it = temp.begin();
auto _2_it = temp.end() - 1;
for (; _2_it > _1_it; _1_it++, _2_it--)
{
if (*_1_it != *_2_it)
return false;
}
return true;
}
void middle_order(TreeNode* root)
{
if (root != NULL)
{
middle_order(root->left);
temp.push_back(root->val);
middle_order(root->right);
}
}
};
中序遍历得到的数组如果对称,树也可能不是镜像的,例如:
所以只能用递归判断的方法了。
class Solution {
public:
bool isSymmetric(TreeNode* root)
{
if (root == NULL) return true;
return ifSymmetric(root->left, root->right);
}
bool ifSymmetric(TreeNode* tree1, TreeNode* tree2)
{
if (tree1 == NULL && tree2 == NULL)
return true;
if (tree1 == NULL || tree2 == NULL)
return false;
if (tree1->val != tree2->val)
return false;
else
return (ifSymmetric(tree1->left, tree2->right) && ifSymmetric(tree1->right, tree2->left));
}
};
Remove Element:
迭代器遍历vector的过程中使用了修改vector的方法(比如vector.erase())就会报错,以前一直以为容器不支持在遍历的同时修改元素,这次看到一份代码,用了一次if else就解决了这个问题,真是学到了。
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
for (auto it = nums.begin(); it != nums.end();)
{
if (*it == val)
it = nums.erase(it);
else
it++;
}
return nums.size();
}
};