繁体   English   中英

python 中二叉树的最大深度

[英]Maximum depth of a binary tree in python

我从二叉树创建了一个元组,它看起来像这样:

元组 = (1,(2,(4,5,6),(7,None,8)),(3,9,(10,11,12)))

通过应用缩进,树结构变得更加清晰:

 (1,  
    (2,
        (4,
            5,
            6
        ),
        (7,
            None,
            8
        )
    ),
    (3,
        9,
        (10,
            11,
            12
        )
    )
)

我知道如何使用递归方法找到二叉树的最大深度,但我正在尝试使用我创建的元组找到最大深度。 谁能帮我怎么做?

如果数据结构的任何元素都不是包含'('')'的字符串,那么这是一个非常有效但相当有效的解决方案。 我会将元组转换为字符串,并解析它以计算括号的深度。

string = str(myTuple)

currentDepth = 0
maxDepth = 0
for c in string:
    if c == '(':
        currentDepth += 1
    elif c == ')':
        currentDepth -= 1

    maxDepth = max(maxDepth, currentDepth)

它给出了元组中转换元组的字符数的线性时间深度。 该数字应该或多或少地与元素数量加上深度成比例,因此您的复杂度有点等于O(n + d)

递归方法:

a = (1,(2,(4,5,6),(7,None,8)),(3,9,(10,11,12)));

def depth(x):
    if(isinstance(x, int) or x == None):
        return 1;
    else:
        dL = depth(x[1]);
        dR = depth(x[2]);
        return max(dL, dR) + 1;

print(depth(a));

想法是通过查看树的左右子树来确定树的深度。 如果节点没有子树,则返回深度1。 否则它返回max(右边深度,左边深度)+ 1

我通过水平顺序遍历解决了这个问题。 如果您知道水平顺序遍历,则可以使用相同的技术解决此问题和https://leetcode.com/problems/binary-tree-right-side-view/问题:

from collections import deque
class Solution:
    def max_depth(self,root):
        if not root:
            return 0
        level=0
        q=deque([root])
        while q:
            # once we exhaust the for loop, that means we traverse all the nodes in the same level
            # so after for loop increase level+=1
            for i in range(len(q)):
                node=q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            level+=1
        return level
class Node(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
   def maxDepth(self, root):
      if not root:
          return 0
      ldepth = self.maxDepth(root.left)
      rdepth = self.maxDepth(root.right)
      return max(ldepth, rdepth) + 1

暂无
暂无

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

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