二叉树的深度
一、题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
二、我的思路
1、先序递归遍历;
2、设置一个全局的变量current,保存当前的深度;
3、遍历到某个节点时候,如果非空,则current增1;
4、遍历完此节点后,current应减1;
三、我的代码
/*
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)
{
int current = 0, result = 0;
traver(pRoot, current, result);
return result;
}
void traver(TreeNode* node, int ¤t, int &result){
if(node == NULL){
return;
}
current++;
if(current > result){
result = current;
}
if(node->left != NULL){
traver(node->left, current, result);
}
if(node->right != NULL){
traver(node->right, current, result);
}
current--;
}
};