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.

 

分析:求二叉树的最大深度

 

解法一:很容易想到的便是递归(深度优先搜索)

(1)如果根节点是空,则返回0;否则转到(2)

   (2)  l = 左子树的最大深度; r = 右子树的最大深度; 返回  max(l, r) + 1;

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode* root) {
13         if(root == NULL)
14             return 0;
15         int l = maxDepth(root->left);
16         int r = maxDepth(root->right);
17         return max(l, r) + 1;
18     }
19 };


解法二:我觉得还可以用广度优先搜索:第i层如果存在节点不为空,则深度加1...最大深度就是这棵树的层数。

 1 class Solution {
 2 public:
 3     int maxDepth(TreeNode* root) {
 4         if(root == NULL)
 5             return 0;
 6         int depth = 0;
 7         queue<TreeNode*> node_que;
 8         TreeNode* temp;
 9         node_que.push(root);
10         while(!node_que.empty()){
11             int size = node_que.size();
12             while(size--){
13                 temp = node_que.front();
14                 node_que.pop();
15                 if(temp->left != NULL)
16                     node_que.push(temp->left);
17                 if(temp->right != NULL)
18                     node_que.push(temp->right);
19             }
20             depth++;
21         }
22         return depth;
23         
24     }
25 };

 

相关文章:

  • 2021-07-20
  • 2021-11-12
  • 2021-05-02
  • 2021-12-10
  • 2021-09-07
  • 2021-06-05
  • 2021-07-22
  • 2021-08-07
猜你喜欢
  • 2021-09-12
  • 2021-08-11
  • 2021-11-10
  • 2021-06-26
  • 2022-12-23
  • 2022-12-23
  • 2021-12-16
相关资源
相似解决方案