首页 > 代码库 > [leetcode]Symmetric Tree @ Python
[leetcode]Symmetric Tree @ Python
原题地址:https://oj.leetcode.com/problems/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
解题思路:这题也不难。需要用一个help函数,当然也是递归的。当存在左右子树时,判断左右子树的根节点值是否相等,如果想等继续递归判断左子树根的右子树根节点和右子树根的左子树根节点以及左子树根的左子树根节点和右子树根的右子树根节点的值是否相等。然后一直递归判断下去就可以了。
# Definition for a binary tree node# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): if root: return self.help(root.left, root.right) return True def help(self, p,q): if p is None and q is None: return True if p and q and p.val == q.val: return self.help(p.left, q.right) and self.help(p.right, q.left) return False
[leetcode]Symmetric Tree @ Python
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。