二叉树的深度
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:每个结点如果他有左或者右结点,那么他的深度就是左子树和右子树深度最大的加一,,利用递归很容易实现。
#include<stdio.h>#include<algorithm>using namespace std;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 max(left,right)+1;}};int main(){return 0;}没有写测试的了。
版权声明:本文为博主原创文章,未经博主允许不得转载。
学习会使你永远立于不败之地。