513. 找树左下角的值、508. 出现次数最多的子树元素和(中等,树)

给定一个二叉树,在树的最后一行找到最左边的值。

示例 1:

输入:

    2
   / \
  1   3

输出:
1
class Solution(object):
    def findBottomLeftValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        #层次遍历,最后一层返回第一个数字
        node=[root]
        while node:
            s=[]
            l=len(node)
            for i in range(l):
                curr=node.pop(0)
                s.append(curr.val)
                if curr.left:
                    node.append(curr.left)
                if curr.right:
                    node.append(curr.right)
        return s[0]

执行用时: 48 ms, 在Find Bottom Left Tree Value的Python提交中击败了80.32%的用户

给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。

示例 1
输入:

  5
 /  \
2   -3

返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。

示例 2

# 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 findFrequentTreeSum(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        d={}
        if not root:
            return []
        def dummy(root):
            if not root:
                return 0
            else:
                s=root.val+dummy(root.left)+dummy(root.right)
                if s not in d:
                    d[s]=1
                else:
                    d[s]+=1
            return s            
        dummy(root)
        maxx=max(d.values())
        result=[i for i in d if d[i]==maxx]
        return result
        

执行用时: 52 ms, 在Most Frequent Subtree Sum的Python提交中击败了96.92%的用户

猜你喜欢

转载自blog.csdn.net/weixin_42234472/article/details/85218176