题解 | #二叉树的深度#
二叉树的深度
http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
树的深度
深搜解法。
首先判定临界条件(深搜终止条件)放回为0,然后二叉树有左右两条路,求最大的那条加上本身根节点非空的深度(1);
如图:开始为1,非空求左树最大深度和右树最大深度的最大值+本身1;
TreeDepth(pRoot->left)时:到节点2,同理左右树最大深度的最大值 + 1(本身),右树为空即2到右树为1深度,左树同理2到4深度为 1+1 = 2;则TreeDepth(pRoot->left)最大为2
同理TreeDepth(pRoot->right):最大为1
则根的最大深度为 max(2,1) + 1 = 3;
/*
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;
return max(TreeDepth(pRoot->left),TreeDepth(pRoot->right))+1;
}
};