如何使用Python在二进制树中获得节点的水平?

发布于 2025-02-09 02:31:37 字数 1696 浏览 2 评论 0原文

我试图在Python中实现二进制树程序。我想添加一个功能以获得特定节点的级别。

例如: -

    10      # level 0
   /  \
  5   15    # level 1
 / \ 
3   7       # level 2

如果我们搜索节点3的级别,则应该返回

class BinaryTree:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
        
    def insert(self, data):
        if self.data == data:
            return
        if self.data<data:
            if self.left:
                self.left.insert(data)
            else:
                self.left = BinaryTree(data)
        else:
            if self.right:
                self.right.insert(data)
            else:
                self.right = BinaryTree(data)
        
    def print_tree(self):
        if self:
            print(self.data)    
        if self.left:
            self.left.print_tree()
        elif self.right:
            self.right.print_tree()
            
    def get_level(self, data, level=0):
        print(type(data))
        level += 1
        if self.data == data:
            return level
        elif self.left and self.right:
            if self.left:
                self.left.get_level(data)
            elif self.right:
                self.right.get_level(data)
        return level
    
    def in_order(self):
        if self:
            #left
            in_order(self.left)
            #root
            print(self.data, '->')
            #right
            in_order(self.right)

这是我的二进制树代码。我需要在此类中添加另一个功能,该函数将在给出值之后,告诉节点的级别

def get_level(node):
    #some code
    return level


get_level(10) # returns the level of the node 10

I tried to implement the binary tree program in python. I want to add one more function to get the level of a specific node.

eg:-

    10      # level 0
   /  \
  5   15    # level 1
 / \ 
3   7       # level 2

if we search the level of node 3, it should return

class BinaryTree:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data
        
    def insert(self, data):
        if self.data == data:
            return
        if self.data<data:
            if self.left:
                self.left.insert(data)
            else:
                self.left = BinaryTree(data)
        else:
            if self.right:
                self.right.insert(data)
            else:
                self.right = BinaryTree(data)
        
    def print_tree(self):
        if self:
            print(self.data)    
        if self.left:
            self.left.print_tree()
        elif self.right:
            self.right.print_tree()
            
    def get_level(self, data, level=0):
        print(type(data))
        level += 1
        if self.data == data:
            return level
        elif self.left and self.right:
            if self.left:
                self.left.get_level(data)
            elif self.right:
                self.right.get_level(data)
        return level
    
    def in_order(self):
        if self:
            #left
            in_order(self.left)
            #root
            print(self.data, '->')
            #right
            in_order(self.right)

This is my code for Binary tree. I need to add another function to this class which will tell the level of a node after giving the value

For example:

def get_level(node):
    #some code
    return level


get_level(10) # returns the level of the node 10

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不即不离 2025-02-16 02:31:37

这对我有用:

def get_level(self, data, level=0):
    print(type(data))
    level += 1
    if self.data == data:
        return level
    if data > self.data:
        if self.left:
            return self.left.get_level(data,level)
    else:
        if self.right:
            return self.right.get_level(data,level)

    return None

对于10级为1,对于5和15为2级,对于3和7,它是3级。

对于0,1,2级别,只需删除“级别+= 1”行并在递归调用中添加级别变量中的+1。

This worked for me:

def get_level(self, data, level=0):
    print(type(data))
    level += 1
    if self.data == data:
        return level
    if data > self.data:
        if self.left:
            return self.left.get_level(data,level)
    else:
        if self.right:
            return self.right.get_level(data,level)

    return None

For the 10 the level will be 1, for 5 and 15 it is level 2, and for 3 and 7 it is level 3.

for the 0,1,2 levels just remove the "level+=1" line and add a +1 in level variable at the recursion call.

岁月苍老的讽刺 2025-02-16 02:31:37

在进行问题之前,您现有代码中存在一些问题:

  • insert方法正在使用树的BST属性(良好),但要去错误的子树以查找插入点的位置。条件如果self.data&lt; data,则应将其倒置为,如果self.data&gt;数据

  • 函数inorder具有递归调用,这些调用函数不是作为方法,而是作为全局函数。因此,这意味着此功能的缩进是错误的。它应该在之外定义,而不是内部。

我需要在此类中添加另一个功能

,您已经拥有该功能,但是它存在以下问题:

  • 该功能返回一个级别,但是当您进行递归调用时,您会忽略该返回的值。
  • 由于您永远不会通过级别的参数,该级别将始终以0开头,因此返回的值将始终为1。
  • 使用elif self.left and self.right您忽略了节点具有的情况一个孩子。
  • 从这是BST的事实中,没有任何好处,因此左右子树都经过遍历,而可以通过遵循单个路径找到数据。

我建议在没有级别参数的情况下执行此操作,然后让函数返回级别,就好像给定节点是根一样。呼叫者可以比递归调用后添加1

    def get_level(self, data):
        if data == self.data:
            return 0
        level = None
        if data < self.data:
            if self.left:
                level = self.left.get_level(data)
        else:
            if self.right:
                level = self.right.get_level(data)
        if level is not None:
            return level + 1

Before getting into your question, there are some issues in your existing code:

  • The insert method is using the BST property of the tree (good), but is going to the wrong subtree to find the location of the insertion point. The condition if self.data<data should be inverted to if self.data > data.

  • The function inorder has recursive calls that call the function not as a method but as a global function. So that means the indentation of this function is wrong. It should be defined outside of the class, not inside.

I need to add another function to this class

You already have that function, but it has these issues:

  • The function returns a level, but when you make the recursive call, you ignore that returned value.
  • As you never pass the level argument, that level will always start with 0 and so the returned value will always be 1.
  • With the elif self.left and self.right you ignore the case where a node has one child.
  • No benefit is taken from the fact that this is a BST, and so both left and right subtrees are traversed, while data can be found by following a single path.

I would suggest to do this without level parameter, and let the function return the level as if the given node were the root. The caller can than add 1 after the recursive call.

    def get_level(self, data):
        if data == self.data:
            return 0
        level = None
        if data < self.data:
            if self.left:
                level = self.left.get_level(data)
        else:
            if self.right:
                level = self.right.get_level(data)
        if level is not None:
            return level + 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文