/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/*class Solution {
public:
bool dfs(TreeNode*r1,TreeNode*r2)//递归
{
if(!r1||!r2)return !r1&&!r2;
return r1->val==r2->val&&dfs(r1->left,r2->right)&&dfs(r1->right,r2->left)
}
bool isSymmetric(TreeNode* root) {
if(!root)return true;
return dfs(root->left,root->right);
}
};*/
class Solution {
public:
bool isSymmetric(TreeNode* root) { //非递归模拟递归
if(!root)return true;
stack<TreeNode*>left,right;
auto l=root->left,r=root->right;
while(l||r||left.size()||right.size())
{
while(l&&r)
{
left.push(l),right.push(r);//左孩子右孩子分别压入两个栈
l=l->left,r=r->right;
}
if(l||r)return false;//如果跳出循环还有不为空说明非镜像
l=left.top(),r=right.top();
left.pop(),right.pop();
if(l->val!=r->val)return false;//判断栈顶元素
l=l->right,r=r->left;//加入右左孩子;
}
return true;
}
};
leetcode 101. 对称二叉树(递归与非递归)
最新推荐文章于 2023-02-17 13:18:15 发布