在树中查找在所有级别中最常出现的节点

时间:2018-03-19 20:39:12

标签: python tree

我最近有一个编码测验,要求我在树中找到一个在所有级别中最常出现的节点。

例如,

      a
     /  \
   c    a
  / \  / \
 c  a b   c

在这棵树中,a应该是答案,因为它出现在0,1和2级。

我尝试使用级别顺序遍历来解决这个问题,但我很困惑如何跟踪节点出现在哪个级别。

我如何解决这个问题,最好是使用Python?

树形结构:

class TreeNode:
    def __init__(self, data = None):
        self.data = data
        self.left = None
        self.right = None

    def insert(self, data):
        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = TreeNode(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = TreeNode(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data

3 个答案:

答案 0 :(得分:2)

当您遍历树时,使用dict来跟踪每个节点类型的显示级别。这可以通过将您的密钥作为节点而将您的值作为节点所在的级别集来实现。

def most_frequent_in_levels(tree):

    counter = {}

    def level_counter(tree, counter, level):
        if tree.data not in counter:
            counter[tree.data] = {level}
        else:
            counter[tree.data].add(level)

        if tree.left:
            level_counter(tree.left, counter, level + 1)

        if tree.right:
            level_counter(tree.right, counter, level + 1)

    level_counter(tree, counter, 0)

    return max(counter.keys(), key=lambda data: len(counter[data]))

这是一个有效的例子。

tree = TreeNode(data='a')
tree.left, tree.right= TreeNode(data='a'), TreeNode(data='b')
tree.left.left, tree.left.right, tree.right.left = TreeNode(data='c'), TreeNode(data='c'), TreeNode(data='c')

# Which creates the following tree
#
#          a
#         /  \
#       a    b
#      / \  /
#     c  c c 

most_frequent_in_levels(tree) # 'a'

答案 1 :(得分:0)

我将如何处理它,这基本上是伪代码和未经测试的

countingdict = {}
for tag, element in root:
   if tag not in dict:
         countingdict.update({tag:1})
   else:
         countingdict[tag] += 1

您可以根据需要将循环嵌套多个级别

答案 2 :(得分:0)

您可以使用自定义版本Breadth-First-Search

from collections import deque, defaultdict
def bsf(tree):
  d = deque([tree])
  levels = defaultdict(list)
  count = 0
  seen = [tree.data]
  while seen:
     listing = []
     while d:
      val = d.popleft()
      if val:
         levels[count].append(val.data)
         listing.extend([val.right, val.left])
     count += 1 
     if not any(listing):
       break
     d.extend(listing)
  return levels


result = bsf(t1)
frequencies = {i:[b for _, b in result.items() if i in b] for i in [c for h in result.values() for c in h]}
last_result = map(frequencies.items(), key=lambda x:len(x[-1]))[0]