简体   繁体   English

如何在二叉树中找到最小值和最大值

[英]How to find the minimum, and maximum value within a Binary Tree

++ EDIT ++ ++ 编辑 ++

Thanks to all of you, I have taken many compartments to get the code to finally working.感谢你们所有人,我花了很多时间让代码最终工作。

Here's the full code overview这是完整的代码概述

class Node:
# Binary Roots: Left and Right, initiating data
def __init__(self, data):
    # Creating an object, Data, to be used for inputs
    self.data = data
    # The objects are defined as None, which creates an empty space for input
    self.left = None
    self.right = None

Define Binary Tree Class:定义二叉树类:

class BinaryTree:二叉树类:

# Defining Roots as Nodes, initiating at the same time.
def __init__(self, rootdata):
    # Declaring roots as new nodes which uses root data
    self.root = Node(rootdata)

Defining FindMax, which will find the maximum value in a binary tree, then return the maximum.定义 FindMax,它会在二叉树中找到最大值,然后返回最大值。

def FindMax(root): def FindMax(根):

# ???
if (root == None):
    return float('-inf')

# In this function, it will search for the maximum of three values, the roots, and maximums from left and right leaves.

# Initialization of 3 things: the maximum of root, and two maximums of left and right leaves
letsfind = root.data
lfound = FindMax(root.left)
rfound = FindMax(root.right)

# If a maximum is found on the left, new maximum is the value.
if(lfound > letsfind):
    letsfind = lfound

# If a maximum is found on the right, new maximum is the value.
if(rfound > letsfind):
    letsfind = rfound

# Return the maximum value found.
return letsfind

??? ???

if name == ' main ':如果名称== ' main ':

# The Inputs of the Binary Tree and leaves.
# root (Top most), root.left (Left Leaf), root.right (Right Leaf)
root = Node(2)
root.left     = Node(7)  
root.right     = Node(5)  
root.left.right = Node(6)  
root.left.right.left= Node(1)  
root.left.right.right= Node(11)  
root.right.right= Node(9)  
root.right.right.left= Node(4)  

# Print the Maximum
print("The Maximum Value in the Binary Tree is: ", FindMax(root))
    

I know it seems long, so I apologize.我知道这似乎很长,所以我道歉。 I have taken account that the function 'FindMax' needs to be outside of the class, in order for it to run properly.我已经考虑到函数“FindMax”需要在类之外,才能正常运行。

One more thing though, what is the purpose of the statement if __name__ == '__main__': ?还有一件事, if __name__ == '__main__':语句的目的是什么?

And What is the if (root == None): return float('-inf') Really for?什么是if (root == None): return float('-inf')真的是为了?

Thanks a lot guys.非常感谢各位。 I appreciate it!我很感激! :) :)

Option 1选项1

The problem is here问题就在这里

st = start.data
lis = start.left
ris = start.right

while you actually call for the data node on st .当您实际调用st上的数据节点时。 The other ones ( lis and ris ) are only been call as Nodes .其他( lisris )仅被称为Nodes You should change it with你应该改变它

st = start.data
lis = (start.left).data
ris = (start.right).data

to be reading the data from all nodes从所有节点读取数据

Option 2选项 2

You override > for your node class.您覆盖>为您的节点类。

Funny but a not for a rookie.有趣但不适合新手。 If you are interested start reading this如果你有兴趣开始阅读 这个

lis = FindMax(start.left) 
ris = FindMax(start.right) 

You forgot to call the recursive search你忘了调用递归搜索

This is the correct code:这是正确的代码:

def findMax(start): 
      
    # Base case  
    if start is None:  
        return float('-inf') 

    st = start.data 
    lis = findMax(start.left)  
    ris = findMax(start.right)  
    
    if (lis > st): 
        st = lis  
    if (ris > st):  
        st = ris  
    
    return st

and call findMax() now并立即调用 findMax()


Tree=BinaryTree("1")
Tree.root.left=Node("2")
Tree.root.right=Node("3")
Tree.root.left.left=Node("4")
Tree.root.left.right=Node("5")
Tree.root.right.left=Node("6")
Tree.root.right.right=Node("7")
Tree.root.right.right.right=Node("8")
print("Maximum element is",  findMax(start)) 

Note - There are a few exceptions to my answer:注意 - 我的回答有一些例外:

  • It may contain errors as OP did not provide the BinaryTree class.它可能包含错误,因为 OP 没有提供 BinaryTree 类。
  • Does not take into account any logical issues.不考虑任何逻辑问题。
  • It is focused on getting OP's code working.它专注于让 OP 的代码工作。

Here are the errors that I spotted:以下是我发现的错误:

  • Python is a language which requires proper indentation. Python 是一种需要适当缩进的语言。 Indentation is vital in-order for code to function properly.缩进对于代码正常运行至关重要。 It appears that the way you have indented your code is incorrect.您缩进代码的方式似乎不正确。
  • When you are trying to call a function inside a class, you would need to make the call either via an instance (self) or the class itself (classmethods).当您尝试在类中调用函数时,您需要通过实例 (self) 或类本身 (classmethods) 进行调用。 Explanation provided here.此处提供说明。
  • Explanation of if __name__ == "__main__": here . if __name__ == "__main__":这里 It is not really required as I assume your code is a single module (in one Python file) but is good to have when working with multiple modules.它不是真正必需的,因为我假设您的代码是单个模块(在一个 Python 文件中),但在使用多个模块时很好。

Based on the points I have mentioned, I have corrected your code accordingly as follows:根据我提到的几点,我已相应地更正您的代码如下:

# Any required imports goes here...
# import XXX


class BinaryTree:
    # OP did not provide code sample...


class Node:
    def __init__(self, data):

        # Creating a node
        self.data = data

        # Pointing either left or right, but it is empty in default
        self.left = None
        self.right = None

    def fmax(self, start):
        
        if start is None:
            return 0

        st = start.data

        lis = self.fmax(start.left)
        ris = self.fmax(start.right)

        if (lis > st):
            st = lis
        if (ris > st):
            st = ris

        return st


if __name__ == "__main__":

    Tree = BinaryTree("1")
    Tree.root.left = Node("2")
    Tree.root.right = Node("3")
    Tree.root.left.left = Node("4")
    Tree.root.left.right = Node("5")
    Tree.root.right.left = Node("6")
    Tree.root.right.right = Node("7")
    Tree.root.right.right.right = Node("8")

    print(Tree.fmax(Tree.root))

If anyone spots any error with my code please feel free to edit it.如果有人发现我的代码有任何错误,请随时对其进行编辑。 My idea is to get OP a working code and he can expand from there.我的想法是让 OP 一个工作代码,他可以从那里扩展。

def findMax(root): 
      
    if (root == None):  
        return float('-inf') 

    res = root.data 
    lres = findMax(root.left)  
    rres = findMax(root.right)  
    if (lres > res): 
        res = lres  
    if (rres > res):  
        res = rres  
    return res 
  
if __name__ == '__main__': 
    root = newNode(2)  
    root.left = newNode(7)  
    root.right = newNode(5)  
    root.left.right = newNode(6)  
    root.left.right.left = newNode(1)  
    root.left.right.right = newNode(11)  
    root.right.right = newNode(9)  
    root.right.right.left = newNode(4)  
  
    print("Maximum element is", findMax(root)) 

#Output #输出

Maximum element is 11最大元素为 11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM