标签:style blog http color io ar for sp div
原题地址: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 = None class 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
标签:style blog http color io ar for sp div
原文地址:http://www.cnblogs.com/asrman/p/3999340.html