题目:
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
结点的定义如下:
struct TreeNode{ int val; TreeNode* left; TreeNode* right; };
思路:
对于树的问题基本都可以通过递归来解决。
一棵二叉树的深度,等于它的左子树深度和右子树深度的较大者+1;
递归的结束条件就是:该结点为空,深度为0;
代码:
struct TreeNode{ int val; TreeNode* left; TreeNode* right; }; int TreeDepth(TreeNode* pRoot){ if(pRoot==NULL) return 0; int left=TreeDepth(pRoot->left); int right=TreeDepth(pRoot->right); return left>right?(left+1):(right+1); }
在线测试OJ:
http://www.nowcoder.com/books/coding-interviews/435fb86331474282a3499955f0a41e8b?rp=2
AC代码:
/* 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==NULL) return 0; int left=TreeDepth(pRoot->left); int right=TreeDepth(pRoot->right); return left>right?(left+1):(right+1); } };