LeetCode: 101. Symmetric Tree
LeetCode: 101. Symmetric Tree
题目描述
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.
题目大意: 判断给定二叉树是否是对称的。
解题思路
判断给定二叉树是否是对称的,只需要判断其左右子树是否对称。而判断两棵二叉树(T1,T2)是否对称,只需要判断:
1. 树根的元素是否相等?
2. T1 的左子树是否和 T2 的右子树对称?
3. T1 的右子树是否和 T2 的左子树对称?
AC代码
- 递归解法
/** * 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 {
// 判断两个二叉树是否对称
bool isSymmetric(TreeNode* leftTree, TreeNode* rightTree)
{
if(leftTree == nullptr || rightTree == nullptr) return (leftTree == rightTree);
if(leftTree->val != rightTree->val) return false;
return isSymmetric(leftTree->left, rightTree->right) &&
isSymmetric(leftTree->right, rightTree->left);
}
public:
bool isSymmetric(TreeNode* root) {
if(root == nullptr) return true;
return isSymmetric(root->left, root->right);
}
};
- 迭代解法
/** * 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) {
if(root == nullptr) return true;
queue<TreeNode*> que;
bool isSym = true;
que.push(root->left);
que.push(root->right);
while(!que.empty())
{
TreeNode* leftTree = que.front();
que.pop();
TreeNode* rightTree = que.front();
que.pop();
if(leftTree == nullptr || rightTree == nullptr) isSym = (leftTree == rightTree);
else if(leftTree->val != rightTree->val) isSym = false;
else
{
que.push(leftTree->left);
que.push(rightTree->right);
que.push(leftTree->right);
que.push(rightTree->left);
}
if(isSym == false) break;
}
return isSym;
}
};