0
点赞
收藏
分享

微信扫一扫

LeetCode_101_对称二叉树

weipeng2k 2022-11-01 阅读 124


题目描述:

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

1
/ \
2 2
\ \
3 3

算法思想:镜像对称树首先根节点必须相同,其次左子树和右子树对称。

/**
* 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 isSymmetric(TreeNode* root) {
return isMirror(root,root);
}
bool isMirror(TreeNode *t1,TreeNode *t2){
if(t1==NULL&&t2==NULL)
return true;
if(t1==NULL||t2==NULL)
return false;
if(t1->val!=t2->val)
return false;
return isMirror(t1->left,t2->right)&&isMirror(t1->right,t2->left);
}

};

LeetCode_101_对称二叉树_子树


算法思想2:设置两个vector,分别存放两种遍历树的值,1、根左右,2、根右左,如果最后连个vector中对应位置的值相同,则说明树是镜像对称树。

/**
* 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:
vector<int> pre;
vector<int> post;
void preorder(TreeNode* root){
if(root==NULL){
pre.push_back(-1);
return;
}
pre.push_back(root->val);
preorder(root->left);
preorder(root->right);
}
void postorder(TreeNode* root){
if(root==NULL){
post.push_back(-1);
return;
}
post.push_back(root->val);
postorder(root->right);
postorder(root->left);
}

bool isSymmetric(TreeNode* root) {
preorder(root);
postorder(root);
vector<int>::iterator it1=pre.begin();
vector<int>::iterator it2=post.begin();
for(;it1!=pre.end()&&it2!=post.end();it1++,it2++){
if(*it1!=*it2)
return false;
}
return true;
}
};

LeetCode_101_对称二叉树_子树_02


举报

相关推荐

0 条评论