leetcode101题 题解 翻译 C语言版 Python版

101. Symmetric Tree

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.

101.对称树
给定一棵二叉树,检查它是否是它自身的镜像(即:轴对称)
举个例子,这棵二叉树是对称的:
    1
   / \
  2   2
 / \ / \
3  4 4  3
但是下面这个就不是:
    1
   / \
  2   2
   \   \
   3    3

思路:这题用递归很好解决,开始时将左子树和右子树分别递归下去,如果第一棵树的左子树和第二棵树的右子树递归下去完全相同,同时第一棵树的右子树和第二棵树的左子树递归下去完全相同,那么这两棵树就满足对称了。如果根结点的两棵子树满足对称了,那么整棵树就是对称的了。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
 
 bool isSymmetriclr(struct TreeNode* left, struct TreeNode* right){
     if (left == NULL && right == NULL) return true;
     if (left == NULL && right != NULL) return false;
     if (left != NULL && right == NULL) return false;
     if (left->val != right->val) return false;
     if (!isSymmetriclr(left->left, right->right)) return false;
     if (!isSymmetriclr(left->right, right->left)) return false;
     return true;
 }
 
bool isSymmetric(struct TreeNode* root) {
    if (root == NULL) return true;
    return isSymmetriclr(root->left, root->right);
}


# 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 isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root: return True
        return self.isSymmetriclr(root.left, root.right)
        
    def isSymmetriclr(self, left, right):
        if not (left or right): return True
        if (left and right==None) or (left==None and right):
            return False
        if left.val != right.val: return False
        if not self.isSymmetriclr(left.left, right.right): return False
        if not self.isSymmetriclr(left.right, right.left): return False
        return True


已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页