LeetCode(104):二叉树的最大深度

Easy!

题目描述:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / 
  9  20
    /  
   15   7

返回它的最大深度 3 。

解题思路:

求二叉树的最大深度问题用到深度优先搜索DFS递归的完美应用,跟求二叉树的最小深度问题原理相同。

C++解法一:

1 class Solution {
2 public:
3     int maxDepth(TreeNode* root) {
4         if (!root) return 0;
5         return 1 + max(maxDepth(root->left), maxDepth(root->right));
6     }
7 };

我们也可以使用层序遍历二叉树,然后计数总层数,即为二叉树的最大深度。

C++解法二:

 1 class Solution {
 2 public:
 3     int maxDepth(TreeNode* root) {
 4         if (!root) return 0;
 5         int res = 0;
 6         queue<TreeNode*> q;
 7         q.push(root);
 8         while (!q.empty()) {
 9             ++res;
10             int n = q.size();
11             for (int i = 0; i < n; ++i) {
12                 TreeNode *t = q.front(); q.pop();
13                 if (t->left) q.push(t->left);
14                 if (t->right) q.push(t->right);
15             }
16         }
17         return res;
18     }
19 };

 

原文地址:https://www.cnblogs.com/ariel-dreamland/p/9162411.html