剑指offer 二叉树的深度

题目:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

分析:恩。。没啥好分析的,很基础的一题,有多种解法,如递归,层次遍历。

解法一:递归

树的深度=max(左子树的深度, 右子树的深度)+ 节点本身的深度(为1)

递归终止条件:如果节点本身为NULL,则返回深度为0.

代码如下:

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     int TreeDepth(TreeNode* pRoot)
13     {
14         if (pRoot == NULL) {
15             return 0;
16         }
17         int left = TreeDepth(pRoot->left);
18         int right = TreeDepth(pRoot->right);
19         return max(left, right) + 1;
20     }
21 };

解法二:层次遍历

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 public:
12     int TreeDepth(TreeNode* pRoot)
13     {
14         queue<TreeNode*> que;
15         int depth = 0;
16         if (pRoot == NULL) {
17             return 0;
18         }
19         que.push(pRoot);
20         while(!que.empty()) {
21             int len = que.size();
22             depth++;
23             for (int i = 0; i < len; i++) {
24                 TreeNode *tmp = que.front();
25                 que.pop();
26                 if (tmp->left != NULL) {
27                     que.push(tmp->left);
28                 }
29                 if (tmp->right != NULL) {
30                     que.push(tmp->right);
31                 }
32             }
33         }
34         return depth;
35     }
36 };
原文地址:https://www.cnblogs.com/qinduanyinghua/p/10474322.html