LeetCode每日一練 二叉樹的最大深度

2021-10-08 14:58:51 字數 1848 閱讀 5128

給定乙個二叉樹,找出其最大深度。

二叉樹的深度為根節點到最遠葉子節點的最長路徑上的節點數。

給定二叉樹[3,9,20,null,null,15,7]

3

/ \9 20

/ \15 7

輸出:3

深度優先

# -*- coding:utf-8 -*-

#構造乙個二叉樹類

class

treenode

:def

__init__

(self,x,y=

none

,z=none):

self.val = x

self.left = y

self.right = z

class

solution

:def

maxdepth

(self, node)

:if node==

none

:return

0return

max(self.maxdepth(node.left)

,self.maxdepth(node.right))+

1

treenode1 = treenode(

3,treenode(9)

,treenode(

20,treenode(15)

,treenode(7)

))result = solution(

)print

(result.maxdepth(treenode1)

)

執行通過了,通過後我把set又刪除了,再執行就沒報錯了,還沒找到原因到底是為啥。

廣度優先

# -*- coding:utf-8 -*-

#構造乙個二叉樹類

import collections

class

treenode

:def

__init__

(self,x,y=

none

,z=none):

self.val = x

self.left = y

self.right = z

class

solution

:def

maxdepth

(self, node)

:if root==

none

:return

0 dep =

0 q = collections.deque(

[node]

)while q:

size =

len(q)

#這裡需要把同一層的都拿出來,所以用for迴圈

for i in

range

(size)

: n = q.popleft(

)if n.left !=

none

:if n.right !=

none

: dep +=

1return dep

treenode1 = treenode(

3,treenode(9)

,treenode(

20,treenode(15)

,treenode(7)

))result = solution(

)print

(result.maxdepth(treenode1)

)

每日一練之二叉樹的深度

方法一 遞迴void treedepthhelper treenode proot,int curr,int max return treedepthhelper proot left,curr 1,max treedepthhelper proot right,curr 1,max inttree...

每日一練(15) 二叉樹的映象

title 每日一練 15 二叉樹的映象 categories 劍指offer tags 每日一練 date 2022 01 28 請完成乙個函式,輸入乙個二叉樹,該函式輸出它的映象。例如輸入 4 2 7 1 3 6 9映象輸出 4 7 2 9 6 3 1示例 1 輸入 root 4,2,7,1,3...

Leetcode 每日一練

最小棧 設計乙個支援 push pop top 操作,並能在常數時間內檢索到最小元素的棧。push x 將元素 x 推入棧中。pop 刪除棧頂的元素。top 獲取棧頂元素。getmin 檢索棧中的最小元素。示例 輸入 minstack push push push getmin pop top ge...