【LeetCode】101 - Symmetric Tree

时间:2023-03-08 16:18:35

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
/ \
2 2
/ \ / \
3 4 4 3

But the following is not:

    1
/ \
2 2
\ \
3 3

Note:Bonus points if you could solve it both recursively and iteratively.

OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
/ \
2 3
/
4
\
5

The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

Solution 1: 递归,left对应right,left->left对应right->right,left->right对应right->left

 /**
* 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)return true;
return isSymTree(root->left,root->right);
}
bool isSymTree(TreeNode *p,TreeNode *q){
if(!isSameNode(p,q))
return false;
else if(!p&&!q)
return true;
else
return isSymTree(p->left,q->right) && isSymTree(p->right,q->left);
}
bool isSameNode(TreeNode *p,TreeNode *q){
if(!p&&!q) //必需加上这个判断条件,否则若p、q为空下面的->val会运行时错误
return true;
else if((!p&&q)||(p&&!q)||(p->val!=q->val)) //利用||的短路效应避免运行时错误
return false;
return true;
}
};

Solution 2 :非递归,待续