题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:
遍历树,然后到叶子节点后深度和max相比较。记录。
代码:
方法一:直接递归
```cpp
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==nullptr)
return 0;
return 1+max(TreeDepth(pRoot->left),TreeDepth(pRoot->right));
}
```cpp
方法二:从上到下走
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
maxnum=0;
ismax(pRoot,0); //后面的参数代表在这层的深度
return maxnum;
}
private:
int maxnum;
void ismax(TreeNode* pnode,int i)
{
if(!pnode) return ; //没节点,直接返回
i++; //表示此时有节点。深度+1
//看左子树
if(!pnode->left)
maxnum= i>maxnum? i :maxnum;
ismax(pnode->left,i);
if(!pnode->right)
maxnum= i>maxnum? i:maxnum;
ismax(pnode->right, i);
return;
}
};