
這題是要找出二元搜尋樹有幾層,用深度搜尋法去找。
LeetCode 題目連結
https://leetcode.com/problems/maximum-depth-of-binary-tree/
題目
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its depth = 3.
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
return its depth = 3.
Accept 作法
Runtime: 0 ms
Memory: 39 MB
- /**
- * Definition for a binary tree node.
- * public class TreeNode {
- * int val;
- * TreeNode left;
- * TreeNode right;
- * TreeNode(int x) { val = x; }
- * }
- */
- class Solution {
- public int maxDepth(TreeNode root) {
- if(root == null)
- return 0;
- int resultLeft = maxDepth(root.left);
- int resultRight = maxDepth(root.right);
- return 1 + Math.max(resultLeft,resultRight);
- }
- }
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。

沒有留言:
張貼留言