Article Directory
Method 1: Whether the left and right subtrees are symmetric, time O(n), space O(n)
Solution: For two symmetrical nodes, there are
- node1->val == node2->val, the two nodes have the same value
- node1->left->val == node1->right->val, the left tree of node1 is the same as the right tree of node2
- node1->right->val == node2->left->val, the right tree of node1 is the same as the left tree of node2
/**
* 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)
{
// 1.判断树的左右树是否对称--》判断两颗树是否相同
// 2.先写出判断两个树是否相同的代码
// 3.然后修改条件变成判断对称
if (root == nullptr)
return true;
return isSyTree(root->left, root->right);
}
bool isSyTree(TreeNode* node1, TreeNode* node2)
{
if (node1 == nullptr && node2 == nullptr)
return true;
if (node1 == nullptr || node2 == nullptr || node1->val != node2->val)
return false;
return isSyTree(node1->left, node2->right) && isSyTree(node1->right, node2->left);
}
};