Leetcode 刷题Day7 404 SumofLeftLeaves 572 Subtree of Another Tree

来源:互联网 发布:全面解读网络安全法 编辑:程序博客网 时间:2024/06/04 01:13
自从昨天理解了python实现链表以后,今天理解python实现树就容易多了
树这种数据结构,理解递归思想对学习树很有帮助。




404 Sum of Left Leaves




Find the sum of all left leaves in a given binary tree.


Example:


    3
   / \
  9  20
    /  \
   15   7


There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.


解题思路:分类讨论
 按左child是叶子还是数讨论


# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def sumOfLeftLeaves(self, root):        """        :type root: TreeNode        :rtype: int        """                        if not root: return 0        if root.left and not root.left.left and not root.left.right:#左子树不是树,是叶子            return root.left.val + self.sumOfLeftLeaves(root.right)        return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)#左子树不是叶子,是树







572. Subtree of Another Tree


Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.


Example 1:
Given tree s:


     3
    / \
   4   5
  / \
 1   2
Given tree t:
   4 
  / \
 1   2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:


     3
    / \
   4   5
  / \
 1   2
    /
   0
Given tree t:
   4
  / \
 1   2
Return false.


解题思路:通过中左右这样的中序遍历把t树和s树转换为字符串,判断t字符串是否在s字符串里(借鉴自该题某discussion)
# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):    def isSubtree(self, s, t):        """        :type s: TreeNode        :type t: TreeNode        :rtype: bool        def convert(p):            return "^" + str(p.val)  + convert(p.left) + convert(p.right) if p else "$"                return convert(t) in convert(s)


        

理解“^”在这里的目的,比如s是单节点树12,t是单节点数2,那么如果不加“^”,则会返回True,因为2在12里,但实际t并不在s里;所以加上“^”以后防止了这种情况,因为^2不在^12里,符合t不在s里的事实。
这种做法跑了115ms,打败了89%的用户。
原创粉丝点击