树:面试题55

面试题55 - I. 二叉树的深度

解题思路:通过层次遍历,将每一层只算一次,进行while循环弹出该层所有数据,在进行下一层入队列。

 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 {
12 public:
13     int maxDepth(TreeNode* root) 
14     {
15         int   lev=0;
16         queue<TreeNode* > q;
17         if (root == NULL)
18             return 0;
19         q.push(root);
20         while (!q.empty() )
21         {
22             ++lev;
23             int len = q.size();
24             while(len--)
25             {
26                 TreeNode* node = q.front();
27                 q.pop();
28                 if (node->left != NULL)
29                     q.push(node->left);
30                 if (node->right != NULL)
31                     q.push(node->right);          
32             }
33         }
34         return lev;
35 
36     }
37 };

解题思路2:递归算法,求得树的最大深度,要设定好结束条件。

 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 {
12 public:
13     int maxDepth(TreeNode* root) 
14     {
15         if (root == NULL)
16             return 0;
17         return max(maxDepth(root->left), maxDepth(root->right) ) + 1; 
18     }
19 };
原文地址:https://www.cnblogs.com/Tavi/p/12750066.html