相關題目
● 104.二叉樹的最大深度 559.n叉樹的最大深度
● 111.二叉樹的最小深度
● 222.完全二叉樹的節點個數
二叉樹的深度與高度
如圖,
二叉樹的深度表示:任意一個葉子節點到根節點的距離,是從上往下計數的,因此使用前序遍歷得到任意一個葉子節點的深度
二叉樹的高度表示:根節點到葉子節點的距離,是從下往上計數的,因此使用后序遍歷得到跟根節點到葉子節點的高度
而二叉樹的最大深度即就是根節點的高度(慢慢品),我的理解:二叉樹的高度表示根節點到最后一層葉子節點的距離,剛好等于二叉樹的最大深度,所以卡哥才這樣總結的
二叉樹的最大深度
由于根節點的高度就是這棵二叉樹的最大深度,因此我們使用后序遍歷求解
遞歸實現:遞歸三部曲
- 確定入參:二叉樹的根節點
- 結束條件:遍歷節點為null時停止
- 單次循環過程:輸出左子樹的高度和右子樹的高度,取最大值
實現過程:
public int maxDepth(Node root) {if(root == null){return 0;}int deep = 0;for (Node chrild:root.children) {int curDeep = maxDepth(chrild);deep = Math.max(deep,curDeep);}return deep+1;}
n叉樹的最大深度
實現過程:
public int maxDepth(Node root) {if(root == null){return 0;}int deep = 0;for (Node chrild:root.children) {int curDeep = maxDepth(chrild);deep = Math.max(deep,curDeep);}return deep+1;}
二叉樹的最小深度
這個玩意不是很好理解
得看視頻回顧回顧:
先上代碼
public int minDepth(TreeNode root) {//后序,求高度if (root == null) {return 0;}int leftDeep = minDepth(root.left);int rightDeep = minDepth(root.right);if(root.left == null && root.right!=null){return rightDeep+1;}if(root.left != null && root.right==null){return leftDeep+1;}return Math.min(leftDeep,rightDeep)+1;}
滿二叉樹的應用
完全二叉樹的節點個數
見下篇文章講解