2020年3月19日 星期四

[LeetCode] 104. Maximum Depth of Binary Tree 解題思路 (Easy)



這題是要找出二元搜尋樹有幾層,用深度搜尋法去找。



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.


Accept 作法



Runtime: 0 ms
Memory: 39 MB

Java
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public int maxDepth(TreeNode root) {
  12. if(root == null)
  13. return 0;
  14. int resultLeft = maxDepth(root.left);
  15. int resultRight = maxDepth(root.right);
  16. return 1 + Math.max(resultLeft,resultRight);
  17. }
  18. }


更多 LeetCode 相關資源

 

複習程式面試書籍


除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備

需要的話可以看看,寫得很仔細。



書名:提升程式設計師的面試力:189道面試題目與解答




相關 LeetCode文章一律會放在 程式解題 標籤分類,歡迎持續追蹤。


沒有留言:

張貼留言