项目作者: eMahtab

项目描述 :
Maximum Depth of Binary Tree
高级语言:
项目地址: git://github.com/eMahtab/maximum-depth-of-binary-tree.git
创建时间: 2020-01-27T06:11:55Z
项目社区:https://github.com/eMahtab/maximum-depth-of-binary-tree

开源协议:

下载


Maximum Depth of Binary Tree ✌️

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.

  1. Example:
  2. Given binary tree [3,9,20,null,null,15,7],
  3. 3
  4. / \
  5. 9 20
  6. / \
  7. 15 7
  8. return its depth = 3.

Implementation 1 : DFS (Recursive)

  1. public int maxDepth(TreeNode root) {
  2. if(root==null)
  3. return 0;
  4. int leftDepth = maxDepth(root.left);
  5. int rightDepth = maxDepth(root.right);
  6. int maxDepth = Math.max(leftDepth, rightDepth);
  7. return maxDepth + 1;
  8. }

Complexity analysis

Time complexity : we visit each node exactly once, thus the time complexity is O(N), where Nis the number of nodes.

Space complexity : in the worst case, the tree is completely unbalanced, e.g. each node has only left child node, the recursion call would occur N times (the height of the tree), therefore the storage to keep the call stack would be O(N). But in the best case (the tree is completely balanced), the height of the tree would be log(N). Therefore, the space complexity in this case would be O(log(N)).

Implementation 2 : Iterative

  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. Queue<TreeNode> q = new ArrayDeque<>();
  15. q.add(root);
  16. int maxDepth = 0;
  17. while(!q.isEmpty()) {
  18. maxDepth++;
  19. int size = q.size();
  20. for(int i = 0; i < size; i++) {
  21. TreeNode current = q.poll();
  22. if(current.left != null)
  23. q.add(current.left);
  24. if(current.right != null)
  25. q.add(current.right);
  26. }
  27. }
  28. return maxDepth;
  29. }
  30. }

😳 Very minute 😳

In the iterative approach make sure you only loop through the size of the queue, that is the size of queue before adding child nodes of the next level. So don’t do this for(int i = 0; i < q.size(); i++) .

References :

https://leetcode.com/articles/maximum-depth-of-binary-tree