2020年4月20日
LeetCode 101. Symmetric Tree
C++, LeetCode, 算法, 编程
0 Comments
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
Follow up: Solve it both recursively and iteratively.
解析:判断一颗二叉树是镜像树,即以根节点左右对称。可以考虑递归和迭代的方法。
递归法:对于两个节点n1和n2,首先判断n1的值是否与n2的值相等,如果不相等在不对称;如果相等,则再判断n1的左子节点和n2的右子节点是否相等,同时n1的右子节点和n2的左子节点是否想相等。代码如下:
/**
* 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* left, TreeNode* right)
{
if(left == NULL && right == NULL)
return true;
if(left == NULL or right == NULL)
return false;
if(left->val != right->val)
return false;
return isSymmetric(left->left, right->right) && isSymmetric(left->right, right->left);
}
bool isSymmetric(TreeNode* root) {
if(root == NULL)
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 == NULL)
return true;
queue<TreeNode*> q1, q2;
q1.push(root->left);
q2.push(root->right);
while(!q1.empty() && !q2.empty())
{
TreeNode* node1 = q1.front();
q1.pop();
TreeNode* node2 = q2.front();
q2.pop();
if(!node1 && !node2)
continue;
if((!node1 && node2) || (node1&&!node2))
return false;
if(node1->val != node2->val)
return false;
q1.push(node1->left);
q1.push(node1->right);
q2.push(node2->right);
q2.push(node2->left);
}
return true;
}
};