[每日一題]104.binary tree level order traversal

1.這是一道二叉樹(shù)查看最深的題目

其中有兩種思路,第一種是BFS,第二種是DFS
他們的時(shí)間復(fù)雜度都是一樣的,反正所有的節(jié)點(diǎn)都會(huì)遍歷一次。
我覺(jué)得遞歸好難想。
BFS:針對(duì)每層遍歷一次,然后記錄每層的長(zhǎng)度,根據(jù)長(zhǎng)度判斷總共有幾層。
DFS:就是每層都加一,然后找到最大的值。這個(gè)的空間復(fù)雜度更好。但是代碼挺難寫的。

104-maximum-depth-of-binary-tree.png

鏈接:
https://leetcode.com/problems/maximum-depth-of-binary-tree/

2.題解:

bfs方法

# bfs方式
    def maxDepth(self, root):
        if root is None:
            return 0
        queue = []
        height = 0
        queue.append(root)
        while queue:
            lenght = len(queue)
            for i in range(lenght):
                node = queue.pop(0)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            height += 1
        return height

dfs方法

    # dfs方式
    def maxDepth(self, root):
        if not root:
            return 0
        return 1+max(self.maxDepth0(root.left), self.maxDepth0(root.right))
3.完整代碼

查看鏈接:
https://github.com/Wind0ranger/LeetcodeLearn/blob/master/8-research/104-maximum-depth-of-binary-tree.py

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容