101.对称二叉树 104.二叉树最大深度
# 101 # 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 def issym(root1,root2): if not root1 and not root2: return True elif root1 and root2 and root1.val == root2.val: return issym(root1.left,root2.right) and issym(root1.right,root2.left) else: return False return issym(root.left,root.right) # 104 # 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 maxDepth(self, root): """ :type root: TreeNode :rtype: int """ def md(root): if not root: return 0 else: return 1+max(md(root.left),md(root.right)) return md(root)递归题目的思路都是差不多的。 把问题分解,并且只去考虑边界情况。 比如,104题,求解二叉树的最大深度。
从根节点出发,最大深度就等于1+max(depth(root.left),depth(root.right)边界条件:如果没有root.left 和 right,那么就return 0将上面两个写成代码