leetcode--101--对称二叉树

2020-09-20  本文已影响0人  minningl

题目:
给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

1

/
2 2
/ \ /
3 4 4 3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

1

/
2 2
\
3 3

链接:https://leetcode-cn.com/problems/symmetric-tree

思路:
1、使用递归的方法判断左右两侧的节点是否对称

Python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    
    def check(self, p, q):
        if not p and not q:
            return True
        if not p or not q:
            return False
        if (p.val==q.val):
            return self.check(p.left, q.right) and self.check(p.right, q.left) 
        else:
            return False

    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        return self.check(root.left, root.right)
        

C++代码:

/**
 * 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 check(TreeNode* p, TreeNode* q){
        if (p==nullptr && q==nullptr) return true;
        if (p==nullptr || q==nullptr) return false;
        if (p->val!=q->val) return false;
        return check(p->left, q->right) && check(p->right, q->left);
    }

    bool isSymmetric(TreeNode* root) {
        if (root == nullptr) return true;
        return check(root->left, root->right);
    }
};
上一篇 下一篇

猜你喜欢

热点阅读