找到你要的答案

Q:Find the longest string in a binary string tree python

Q:找到一个二进制字符串的字符串最长树蟒

Alright so I need to define a recursive function longest_length() that takes a binary string tree and returns the length of the longest string in the tree.

I admittedly have no clue how to do this, but this is what I have set up:

def add_leaves(bnt):
    """Takes a BNT and returns the length of the largest string in the tree.

    BNT - number"""
    if isinstance(bnt, str):
        return bnt
    else:
        return ????

can anyone help me out? this isn't really homework, just a question I came upon while studying for finals that I feel I should know how to answer

好吧,那么我需要定义一个递归函数longest_length()以二进制字符串返回树和树中的最长的字符串的长度。

我不知道该怎么做,但这是我所设置的:

def add_leaves(bnt):
    """Takes a BNT and returns the length of the largest string in the tree.

    BNT - number"""
    if isinstance(bnt, str):
        return bnt
    else:
        return ????

有人能帮我吗?这不是真正的功课,只是一个问题,我在研究的总决赛时,我觉得我应该知道如何回答

answer1: 回答1:

Assuming you have a tree node class that has a string value attribute, and attributes to store its left and right children, the implementation would be fairly simple:

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def find_max(node):
    if (node is None): return ""
    return max([find_max(node.left), node.val, find_max(node.right)], key=len)

tree = TreeNode("test", TreeNode("asdasjkdnaskdjasd", TreeNode("")), TreeNode("a"))
print find_max(tree) # asdasjkdnaskdjasd

You can see a demo here: http://ideone.com/SE39tM

假设你有一个树节点类,它有一个字符串值属性,属性用来存储它的左右子,那么这个实现就相当简单了:

class TreeNode:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def find_max(node):
    if (node is None): return ""
    return max([find_max(node.left), node.val, find_max(node.right)], key=len)

tree = TreeNode("test", TreeNode("asdasjkdnaskdjasd", TreeNode("")), TreeNode("a"))
print find_max(tree) # asdasjkdnaskdjasd

你可以看到在这里演示:http://ideone.com/se39tm

python  string  binary-tree