Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
Note:
Bonus points if you could solve it both recursively and iteratively.
解题思路
思路一:只需要判断左子树和右子树是否对称即可,因此可以将原问题归结为判断两棵二叉树是否互为镜像。
首先比较两个根结点 r1 和 r2 的值是否相等,然后递归判断 r1 的左子树和 r2 的右子树是否互为镜像以及 r1 的右子树和 r2 的左子树是否互为镜像。
代码如下:
/**
* 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 isMirror(TreeNode *tree1, TreeNode *tree2) {
if (tree1 == NULL && tree2 == NULL) return true;
if (tree1 == NULL || tree2 == NULL) return false;
if (tree1->val != tree2->val) return false;
return isMirror(tree1->left, tree2->right) && isMirror(tree1->right, tree2->left);
}
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL) return true;
return isMirror(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;
stack<TreeNode *> nodeStack;
nodeStack.push(root->left);
nodeStack.push(root->right);
while (!nodeStack.empty()) {
TreeNode *tree1 = nodeStack.top();
nodeStack.pop();
TreeNode *tree2 = nodeStack.top();
nodeStack.pop();
if (tree1 == NULL && tree2 == NULL) continue;
if (tree1 == NULL || tree2 == NULL) return false;
if (tree1->val != tree2->val) return false;
nodeStack.push(tree1->left);
nodeStack.push(tree2->right);
nodeStack.push(tree1->right);
nodeStack.push(tree2->left);
}
return true;
}
};