题目描述:
LeetCode 501. Find Mode in Binary Tree
Given a binary tree with duplicates. You have to find all the mode(s) in given binary tree.
For example:
Given binary tree [1,null,2,2]
,
1 \ 2 / 2
return [2]
.
Note: If a tree has more than one mode, you can return them in any order.
题目大意:
给定一棵包含重复元素的二叉树。寻找其中的所有众数。
注意:二叉树可能包含多个众数,以任意顺序返回即可。
解题思路:
二叉树遍历 + 计数
Python代码:
# 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 findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
counter = collections.Counter()
def traverse(root):
if not root: return
counter[root.val] += 1
traverse(root.left)
traverse(root.right)
traverse(root)
maxn = max(counter.values() + [None])
return [e for e, v in counter.iteritems() if v == maxn]
本文链接:http://bookshadow.com/weblog/2017/01/29/leetcode-find-mode-in-binary-tree/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。