法一:中序遍历
有3个样例不能通过测试。其中一个是
[1,2,2,2,null,2]
预期:False
返回:True
没搞懂。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
#左右子树中序遍历对称
def inorder(root):
if not root:
return [0]
pre=inorder(root.left)
pre.append(root.val)
post=inorder(root.right)
pre.extend(post)
return pre
if inorder(root.left)!=inorder(root.right)[::-1]:
return False
return True
法二:递归
执行用时:44 ms, 在所有 Python3 提交中击败了59.76%的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了27.80%的用户
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
#递归
def helper(p,q):
if p==None and q==None:
return True
if (q and not p) or (p and not q):
return False
return p.val==q.val and helper(p.left,q.right) and helper(p.right,q.left)
return not root or helper(root.right,root.left)
法三:C++迭代
执行用时: 8 ms , 在所有 C++ 提交中击败了50.29% 的用户
内存消耗:16.1 MB , 在所有 C++ 提交中击败了17.10% 的用户
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool check(TreeNode*u,TreeNode*v){
queue<TreeNode*> q;
q.push(u);q.push(v);
while(!q.empty()){
u=q.front();q.pop();
v=q.front();q.pop();
if(!u&&!v) continue;
if((!v||!u)||(u->val!=v->val)) return false;
q.push(u->left);
q.push(v->right);
q.push(u->right);
q.push(v->left);
}
return true;
}
bool isSymmetric(TreeNode* root) {
return check(root,root);
}
};