题目:二叉树的深度
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路
遍历二叉树,用depth记录当前深度,用now记录最大值
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void GetDepth(TreeNode *r, int depth, int &now){
if(now<depth) now=depth;
if(r->left) GetDepth(r->left, depth+1, now);
if(r->right) GetDepth(r->right, depth+1, now);
}
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot) return 0;
int depth=0, now=0;
GetDepth(pRoot, depth+1, now);
return now;
}
};
思路②用层次遍历,queue来完成,代码不写了
后来发现有更简单的代码
/*
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)
{
if(!pRoot) return 0;
int left = TreeDepth(pRoot->left);
int right = TreeDepth(pRoot->right);
return left>right?left+1:right+1;
}
};