簡體   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