其他分享
首页 > 其他分享> > leetcode刷题笔记 101.对称二叉树【简单】

leetcode刷题笔记 101.对称二叉树【简单】

作者:互联网

1、递归

bool helper(TreeNode* lnode, TreeNode* rnode) {
	if (lnode == NULL && rnode == NULL)
		return true;
	else if (lnode == NULL || rnode == NULL)
		return false;
	else if (lnode->val == rnode->val)
		return helper(lnode->left, rnode->right) && helper(lnode->right, rnode->left);
	return false;
}


bool isSymmetric(TreeNode* root) {
	return helper(root, root);
}

在这里插入图片描述
2、迭代(广度优先搜索)

bool isSymmetric(TreeNode* root) {
	//广度优先搜索
	queue<TreeNode*> q;
	TreeNode* lnode = root, * rnode = root;
	q.push(lnode);
	q.push(rnode);
	while (!q.empty()) {
		lnode = q.front();
		q.pop();
		rnode = q.front();
		q.pop();
		if (lnode->val != rnode->val)
			return false;
		if (lnode->left != NULL && rnode->right != NULL) {
			q.push(lnode->left);
			q.push(rnode->right);
		}
		else if (((lnode->left == NULL) ^ (rnode->right == NULL)) == 1)
			return false;
		if (lnode->right != NULL && rnode->left != NULL) {
			q.push(lnode->right);
			q.push(rnode->left);
		}
		else if (((lnode->right == NULL) ^ (rnode->left == NULL)) == 1)
			return false;
	}
	return true;
}

在这里插入图片描述

标签:NULL,return,lnode,rnode,right,二叉树,101,leetcode,left
来源: https://blog.csdn.net/weixin_46477226/article/details/119320878