基于和的二叉树

2024-09-30 01:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须为二叉树中的每一级实现一个求和 我必须返回一个列表,该列表在位置I处包含第I个和 如果我有这棵树

      24
    /   \
   14    27
  / \  /  \
11  20 12  55

我必须返回[24,41,98]

我试图用python实现这个解决方案

def sommaperlivelli(p, lista):
if p == None:
    return 
if p.left != None and p.right != None:
    lista.append(p.left.key + p.right.key)
sommaperlivelli(p.left, lista)
sommaperlivelli(p.right, lista)
return lista

我只能得到第一个和,不能加根。我怎么能做到

这是我使用的类

class NodoABR:
def __init__(self, key = None, left = None, right = None, parent = None):
    self.key = key
    self.left = left
    self.right = right
    self.parent = parent

这就是我如何将节点添加到树中的方法

def inserisciNodo(p, n):
if p == None:
    return NodoABR(n)
else:
    if p.key == n:
        return p
    elif p.key < n:
        rchild = inserisciNodo(p.right, n)
        p.right = rchild
        rchild.parent = p
    else:
       lchild = inserisciNodo(p.left, n)
       p.left = lchild
       lchild.parent = p 
return p

这是一个二进制搜索树 在主要功能中,我这样做

p = NodoABR(24)
p = inserisciNodo(p, 14)
p = inserisciNodo(p, 27)
p = inserisciNodo(p, 11)
p = inserisciNodo(p, 20)
p = inserisciNodo(p, 12)
p = inserisciNodo(p, 55)
print(sommaperlivelli(p,[]))

Tags: keyselfrightnonereturnifdefleft
2条回答

假设您有类似的树节点类,您可以试试这个&;修改以满足您的特殊需要

from collections import deque

class Node:     # TreeNode eg.
    def  __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
    
def LevelSum(root):
    answer = []
    
    if (root == None):  return 0        # base case

    result = root.data
    
    # track of # nodes at every level when traversal, and sum them up
    q = deque()
    q.append(root)
    
    while len(q):             #  > 0):
        size = len(q)

    # Iterate for all the nodes
        tot = 0   
         
        while size:      # meaning  - size > 0 
        # Dequeue an node from queue
            tmp = q.popleft()

        # Add this node's value to current sum.
            tot += tmp.data

        # Enqueue left and right children of dequeued node
            if (tmp.left != None):  q.append(tmp.left)
                
            if (tmp.right != None): q.append(tmp.right)
            
            size -= 1
        print(tot, result)

        answer.append(tot)
        
    return answer

例如:

if __name__ == '__main__':
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right.right = Node(6)
    root.right.right.left = Node(9)
    root.right.right.right = Node(11)
    """
    # Constructed Binary tree is:
    #          1
    #        /  \
    #        2   3                 #  5
    #       / \   \
    #      4 5     6               # 15
    #             / \
    #             9   11           # 20
    """
    print("level sum is", LevelSum(root))

[编辑]PO作者想学习另一种方法。(非排队)

from collections import Counter
from typing import List


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


def level_sum(root: Node) -> int:
    
    def dfs(node, level):
        if not node: return
        
        total[level] += node.data
        dfs(node.left,level  + 1)
        dfs(node.right,level + 1)
        
    total = Counter()
    dfs(root, 1)

    print(total)     # showing each level & its total   - can be commented out 
    
    return total.most_common()[0][1]    # the largest total

使用您的NodoABR类,这里有一个简单的树遍历,深度优先,我们注意到每个迭代的级别,并使用它存储节点值,arr是一个列表数组(或列表),每个级别一个:

# Create sample tree
root = NodoABR(24, NodoABR(14, NodoABR(11), NodoABR(20)), NodoABR(27, NodoABR(12), NodoABR(55)))

def handle_node(nd, level):
    # Add a new level list if needed
    if len(arr) == level:
        arr.append([])
    # Append this node value to its proper level list
    arr[level].append(nd.key)

    # Recurse, increasing the level
    if nd.left is not None:
        handle_node(nd.left, level+1)
    if nd.right is not None:
        handle_node(nd.right, level+1)

# Main program
arr = []
handle_node(root, 0)
print(arr)

这是输出:

[[24], [14, 27], [11, 20, 12, 55]]

相关问题 更多 >

    热门问题