LeetCode - 解题笔记 - 101 - Symmetric Tree

Solution 1

其实是对 0100. Same Tree 的变体,对称的二叉树,就是二者镜像相同,对前一个题的逻辑稍加改造即可。这里是DFS实现。

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N为节点个数,最坏情况检查整棵树
  • 空间复杂度: O ( N ) O(N) O(N),其中 N N N为节点个数,最坏情况下,这是一棵非常skew的树
/**
 * 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 isSymmetric(TreeNode* root) {
        return this->isSame1(root->left, root->right);
    }
    
private:
    bool isSame1(TreeNode* p, TreeNode* q) {
        if (p == nullptr && q == nullptr) {
            return true;
        } else if (p == nullptr || q == nullptr) {
            return false;
        } else if (p->val != q->val) {
            return false;
        } else {
            return isSame1(p->left, q->right) && isSame1(p->right, q->left);
        }
    }
};

Solution 2

这里是BFS实现。

  • 时间复杂度: O ( N ) O(N) O(N),其中 N N N为节点个数,最坏情况检查整棵树
  • 空间复杂度: O ( N ) O(N) O(N),其中 N N N为节点个数,最坏情况下,这是一棵非常skew的树
/**
 * 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 isSymmetric(TreeNode* root) {
        // return this->isSame1(root->left, root->right);
        return this->isSame2(root->left, root->right);
    }
    
private:
    bool isSame2(TreeNode* p, TreeNode* q) {
        if (p == nullptr && q == nullptr) {
            return true;
        } else if (p == nullptr || q == nullptr) {
            return false;
        }
        
        queue <TreeNode*> qp, qq;
        qp.push(p);
        qq.push(q);
        // cout << "NOW" << (p->val) << " " << (q->val) << endl;
        while (!qp.empty() && !qq.empty()) {
            auto curp = qp.front();
            qp.pop();
            auto curq = qq.front();
            qq.pop();
            // cout << "NOW" << (curp->val) << " " << (curq->val) << endl;
            if (curp->val != curq->val) { 
                return false;
            } else {
                auto leftp = curp->left;
                auto leftq = curq->right;
                
                if (leftp != nullptr && leftq != nullptr) {
                    qp.push(leftp);
                    qq.push(leftq);
                    // cout << (leftp->val) << " " << (leftq->val);
                } else if (leftp == nullptr ^ leftq == nullptr) {
                    return false;
                }
                
                auto rightp = curp->right;
                auto rightq = curq->left;
                
                if (rightp != nullptr && rightq != nullptr) {
                    qp.push(rightp);
                    qq.push(rightq);
                    // cout << "LOAD" << rightp->val << " " << rightq->val;
                } else if (rightp == nullptr ^ rightq == nullptr) {
                    return false;
                }
            }
        }
        
        return qp.empty() && qq.empty();
    }
};

Solution 3

Solution 1的Python实现

# 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: Optional[TreeNode]) -> bool:
        return self.isSame1(root.left, root.right)
    
    def isSame1(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if p is None and q is None:
            return True
        elif p is None or q is None:
            return False
        elif p.val != q.val:
            return False
        else:
            return self.isSame1(p.left, q.right) and self.isSame1(p.right, q.left)

Solution 4

Solution 2的Python实现

# 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: Optional[TreeNode]) -> bool:
        # return self.isSame1(root.left, root.right)
        return self.isSame2(root.left, root.right)

    def isSame2(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if p is None and q is None:
            return True
        elif p is None or q is None:
            return False
        
        qp = collections.deque([p])
        qq = collections.deque([q])
        
        # print(p.val, q.val)
        while qp and qq:
            curp = qp.popleft()
            curq = qq.popleft()
            # print("NOW", curp.val, curq.val)
            if curp.val != curq.val:
                return False
            else :
                leftp, leftq = curp.left, curq.right
                if leftp is not None and leftq is not None:
                    qp.append(leftp)
                    qq.append(leftq)
                    # print("LEFT", leftp.val, leftq.val)
                elif (leftp is None) ^ (leftq is None):
                    return False
                
                rightp, rightq = curp.right, curq.left
                if rightp is not None and rightq is not None:
                    qp.append(rightp)
                    qq.append(rightq)
                    # print("RIGHT", rightp.val, rightq.val)
                elif (rightp is None) ^ (rightq is None):
                    return False

        return not qp and not qq
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值