劍指Offer 二叉樹的深度

2021-10-09 22:44:59 字數 1074 閱讀 6332

輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度為樹的深度。

dfs(深搜優先搜尋)或者bfs(廣度優先搜尋)都行。

dfs:

/**

public class treenode }*/

public

class

solution

getmaxdepth

(root,0)

;return maxdepth;

}void

getmaxdepth

(treenode root,

int depth)

getmaxdepth

(root.left, depth +1)

;getmaxdepth

(root.right, depth +1)

;}}

dfs簡潔版:

/**

public class treenode }*/

public

class

solution

int left =

treedepth

(root.left)

;int right =

treedepth

(root.right)

;return left > right ? left +

1: right +1;

}}

bfs:

/**

public class treenode }*/

public

class

solution

queue

que =

newlinkedlist

<

>()

;int depth =0;

que.

add(root)

;while

(!que.

isempty()

)}return depth;

}}

劍指offer 二叉樹的深度

輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點 含根 葉結點 形成樹的一條路徑,最長路徑的長度為樹的深度。如果二叉樹只有根節點那麼深度就是1,如果只有左子樹,那麼就是左子樹的深度加1就是整棵二叉樹的深度 如果只有右子樹,那麼二叉樹的深度就是右子樹的深度加1 如果既有左子樹又有右子樹,那...

劍指offer 二叉樹的深度

輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點 含根 葉結點 形成樹的一條路徑,最長路徑的長度為樹的深度。思路 面對樹形結構,我們常用的演算法就是遞迴,根樹的每一塊子樹都可以看成一棵小的完整的樹,這位我們解題提供了很好的思路。如果一開始傳入的就是空的那麼深度就是0,如果不是0,那麼這顆...

劍指offer 二叉樹的深度

class solution def treedepth self,proot write code here if proot none return 0 return max 1 self.treedepth proot.left 1 self.treedepth proot.right 非常簡...