简体   繁体   English

如何使用python获取二叉树中节点的级别?

[英]How to get the level of a node in binary tree using python?

I tried to implement the binary tree program in python.我试图在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如果我们搜索节点 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)

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

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. 10 级为 1 级,5 和 15 级为 2 级,3 和 7 级为 3 级。

for the 0,1,2 levels just remove the "level+=1" line and add a +1 in level variable at the recursion call.对于 0,1,2 级别,只需删除“级别+=1”行并在递归调用中添加级别变量中的 +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. insert方法是使用树的 BST 属性(好),但是会去错误的子树寻找插入点的位置。 The condition if self.data<data should be inverted to if self.data > data .条件if self.data<data应反转为if self.data > data

  • The function inorder has recursive calls that call the function not as a method but as a global function.函数inorder具有递归调用,这些调用不是作为方法而是作为全局函数调用该函数。 So that means the indentation of this function is wrong.所以这意味着这个函数的缩进是错误的。 It should be defined outside of the class , not inside.它应该定义在class之外,而不是内部。

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.由于您从不传递 level 参数,因此该级别将始终以 0 开头,因此返回的值将始终为 1。
  • With the elif self.left and self.right you ignore the case where a node has one child.使用elif self.left and self.right您可以忽略节点有一个孩子的情况。
  • 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.这是一个 BST,因此没有任何好处,因此左右子树都被遍历,而数据可以通过单条路径找到。

I would suggest to do this without level parameter, and let the function return the level as if the given node were the root.我建议在没有level参数的情况下执行此操作,并让函数返回级别,就好像给定节点是根节点一样。 The caller can than add 1 after the recursive call.调用者可以在递归调用之后添加 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

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

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