101. 对称二叉树

101. 对称二叉树

法一:中序遍历

有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);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值