简体   繁体   English

如何获得非常大的二叉树中节点的级别?

[英]How do I obtain the level of a node in a very large binary tree?

I'm doing a coding challenge in which I'm to find the level of a node in a binary tree of tuples if it exists.我正在做一个编码挑战,如果存在,我将在元组的二叉树中找到节点的级别。 My solution isn't efficient and works only for low level nodes.我的解决方案效率不高,仅适用于低级节点。 How do I optimize the code to work for very large levels?如何优化代码以适用于非常大的级别?

The generating pattern of the tuples is in the Node class.元组的生成模式在节点 class 中。

from itertools import product

class Node:
    def __init__(self,data):
        self.data = data
        self.left = (self.data[0] + self.data[1], self.data[1])
        self.right = (self.data[0], self.data[0] + self.data[1])

    def lefts(self):
        self.data = self.left

    def rights(self):
        self.data = self.right

    def getter(self):
        return self.data

def solution(x,y):
    tup = (int(x),int(y))
    a = ['left', 'right']
    directions = list(product(a,repeat=int(max(tup))))

    for direction in directions:
        node = Node((1,1))
        count = 0
        for lor in direction:
            if node.getter() == tup:
                return count
            if lor == 'left':
                node.lefts()
                node = Node(node.getter())
            else:
                node.rights()
                node = Node(node.getter())
            count += 1
            
    return 'impossible'

For this problem it is overkill to actually create a binary tree.对于这个问题,实际创建二叉树是多余的。

What is more, it is better to look at the problem in the opposite direction, ie start at the given (x,y) "node" and determine what its parent would be, and then repeat that step to walk towards the root.更重要的是,最好从相反的方向看问题,即从给定的(x,y)“节点”开始并确定其父节点是什么,然后重复该步骤以走向根节点。

This is more interesting, since a node has only one parent, and so no alternatives have to be considered.这更有趣,因为一个节点只有一个父节点,因此不必考虑替代方案。 If this path leads to the node (1, 1), then we found the solution.如果这条路径通向节点 (1, 1),那么我们找到了解决方案。 If however the path leads to a tuple that has a member that is not strictly positive, then we can conclude there is no solution... apparently the node is member of a distinct tree.然而,如果路径导致一个元组的成员不是严格正数,那么我们可以得出结论没有解决方案......显然该节点是不同树的成员。

The "formula" to get the parent node of (x, y) is获取 (x, y) 的父节点的“公式”是

  • (x, y - x) when y > x (x, y - x) 当 y > x
  • (x - y, y) otherwise (x - y, y) 否则

Based on these observations, the program is quite straightforward:基于这些观察,该程序非常简单:

def solution(x, y):
    count = 0
    while x > 1 and y > 1:
        if x > y:
            x -= y
        else:
            y -= x
        count += 1
    return count + abs(x - y) if min(x, y) == 1 else "impossible"

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

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