"Symmetric Tree" and "Remove Element"

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();
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值