【树】104. 二叉树的最大深度

题目:

解答:

方法一:递归的方法

可以很容易用递归解决这个问题,为什么呢?因为一个节点的左孩子和右孩子是该节点的子树。首先,计算左子树的最大高数,然后计算右子树的高度。

因此,当前节点的最大高度就是max(左子树的最大高度, 右子树的最大高度)+1。

基于以上事实,当前节点为空时,返回0;NULL表示没有树,所以它的最大高度是0.

具体代码如下:

 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     {
14         if (NULL == root)
15         {
16             return 0;
17         }
18 
19         // 这是求二叉树的最大深度
20         int maxdepth = std::max(maxDepth(root->left), maxDepth(root->right)) + 1;
21 
22         return maxdepth;
23     }
24 };

方法二:广度优先遍历

 1 class Solution 
 2 {
 3  public:
 4      int maxDepth(TreeNode *root)
 5      {
 6          int rtn = 0;
 7          queue<TreeNode*> q;
 8 
 9          if(NULL != root)
10          {
11              q.push(root);
12              q.push(NULL);
13          }
14 
15          while(q.empty() != NULL )
16          {
17              TreeNode *cur = q.front();
18              q.pop();
19 
20              if(NULL == cur)
21              {
22                  rtn++;
23                  if( q.size() ) //当cur == NULL时,说明该层已经遍历结束,如果队列不为空,说明还有下一层,然后把NULL压入队列,作为下一层结束标志;若为空,则结束了
24                  {
25                      q.push(NULL);
26                  }
27              }
28              else
29              {
30                  if(cur->left)
31                  {
32                      q.push(cur->left);
33                  }
34                  if(cur->right)
35                  {
36                      q.push(cur->right);
37                  }
38              }
39          }
40          return rtn;
41      }
42  };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12817634.html