文章目录
0. 题目相关
【题目解读】
给定两颗二叉树,对这两颗二叉树进行比较,判断这两棵二叉树是否对称
【原题描述】原题链接
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
【难度】Easy
1. Solution
自己用的中根序遍历根节点的左右子树,然后进行比较。发现这种方法对于例子中**[1,2,2,null,3,null,3]**这种情况就不能正确判断,还需要进行修改。
有问题的代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#define Max_Size 100
#include <stack>
class Solution {
private:
//由于有ret这个数组,不能使用递归版本
int inOrder(TreeNode* root, int ret[])
{
int index = 0;
stack<TreeNode*> Tstack;
TreeNode* pre = root;
while(pre != NULL && !Tstack.empty())
{
if(pre != NULL)
{
Tstack.push(pre);
pre = pre->left;
}else
{
pre = Tstack.top();
ret[index++] = pre->val;
pre = pre->right;
Tstack.pop();
}
}
return index;
}
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL)
return false;
int lTree[Max_Size] = {0};
int rTree[Max_Size] = {0};
TreeNode *left = root->left;
TreeNode *right = root->right;
int lLen = inOrder(left, lTree);
int rLen = inOrder(right, rTree);
if(lLen != rLen)
return false;
for(int index = 0; index < lLen; index ++)
{
if(lTree[index] != rTree[rLen-index])
return false;
}
return true;
}
};