LeetCode 104. Maximum Depth of Binary Tree

欢迎访问原文所在博客:52Heartz’s Blog

题目来源:https://leetcode.com/problems/maximum-depth-of-binary-tree/

LeetCode官方题解及解析:104. 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.

解答1[Java]:递归算法

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.lang.Math;
class Solution {
  public int maxDepth(TreeNode root) {
    if (root == null) {
      return 0;
    } else {
      int left_height = maxDepth(root.left);
      int right_height = maxDepth(root.right);
      return Math.max(left_height, right_height) + 1;
    }
  }
}

复杂度分析

  • Time complexity : we visit each node exactly once, thus the time complexity is O ( N ) O(N) O(N), where N N N is 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 N N times (the height of the tree), therefore the storage to keep the call stack would be O ( N ) O(N) O(N). But in the best case (the tree is completely balanced), the height of the tree would be l o g ( N ) log(N) log(N). Therefore, the space complexity in this case would be O ( l o g ( N ) ) O(log(N)) O(log(N))

    completely unbalanced would looks like this

        3
         \
         20
           \
            7
             \
              9
               \
                15
    

    completely balanced would looks like this:

            3
         /     \
        9       20
       / \     /  \
      8   4   15   7
    

解答2[Java]:非递归,深度优先遍历

使用 Stack 数据结构进行深度优先遍历。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import javafx.util.Pair;
import java.lang.Math;
class Solution {
  public int maxDepth(TreeNode root) {
    LinkedList<Pair<TreeNode, Integer>> stack = new LinkedList<>();
    if (root != null) {
      stack.add(new Pair(root, 1));
    }

    int depth = 0;
    while (!stack.isEmpty()) {
      Pair<TreeNode, Integer> current = stack.pollLast();
      root = current.getKey();
      int current_depth = current.getValue();
      if (root != null) {
        depth = Math.max(depth, current_depth);
        stack.add(new Pair(root.left, current_depth + 1));
        stack.add(new Pair(root.right, current_depth + 1));
      }
    }
    return depth;
  }
};

复杂度分析

  • Time complexity : O ( N ) O(N) O(N).
  • Space complexity : O ( N ) O(N) O(N).

解答3[Java]:非递归,广度优先遍历

使用 Queue 数据结构进行深度优先遍历。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        int depth = 0;
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            depth++;
        }
 
        return depth;
    }
}

复杂度分析

  • Time complexity : O ( N ) O(N) O(N).
  • Space complexity : O ( N ) O(N) O(N).

LinkedList 类的相关方法

简单介绍本题中用到的 LinkedList 类的几个方法。

add(E e)

Appends the specified element to the end of this list.

poll()

Retrieves and removes the head (first element) of this list.

pollLast()

Retrieves and removes the last element of this list, or returns null if this list is empty.

参考文献

LinkedList (Java Platform SE 8 )

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值