1. 程式人生 > 其它 >LeetCode刷題進階之二叉樹的最大深度/ 二叉樹的深度 (104/劍指 Offer 55 - I)

LeetCode刷題進階之二叉樹的最大深度/ 二叉樹的深度 (104/劍指 Offer 55 - I)

技術標籤:LeetCodeleetcode二叉樹DFS/BFSjava

一、題目
在這裡插入圖片描述
演示示例:
在這裡插入圖片描述
二、測試程式碼

//方法一 遞迴(DFS)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution { public int maxDepth(TreeNode root) { if(root==null){ return 0; } int leftDepth=maxDepth(root.left); int rightDepth=maxDepth(root.right); return Math.max(leftDepth,rightDepth)+1; } } //方法二 非遞迴(BFS) /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */
class Solution { public int maxDepth(TreeNode root) { if(root==null) { return 0; } Queue<TreeNode> queue=new LinkedList<>(); queue.offer(root); int res=0; while(!queue.isEmpty()) { int size=queue.size(); while(size>0) { TreeNode temp=queue.poll(); if
(temp.left!=null) { queue.offer(temp.left); } if(temp.right!=null) { queue.offer(temp.right); } size--; } res++; } return res; } }

三、執行情況

方法一:
在這裡插入圖片描述
方法二:
在這裡插入圖片描述
傳送門:二叉樹最大深度(高度)/結點個數 / 葉子結點個數 / 第k層結點個數的求解