NC274. 二叉树的深度
描述
示例1
输入:
{1,2,3,4,5,#,6,#,#,7}
输出:
4
示例2
输入:
{}
输出:
0
C++ 解法, 执行用时: 2ms, 内存消耗: 352KB, 提交时间: 2021-05-29
/* 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=(pRoot->left!=NULL)?TreeDepth(pRoot->left):0; int right=(pRoot->right!=NULL)?TreeDepth(pRoot->right):0; return left<right?right+1:left+1; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 352KB, 提交时间: 2020-11-05
/* 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 lnum = TreeDepth(pRoot->left); int rnum = TreeDepth(pRoot->right); return 1+(lnum > rnum ? lnum : rnum); } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-06-05
/* 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!=nullptr) return max(TreeDepth(pRoot->left),TreeDepth(pRoot->right))+1; else return 0; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-04-17
/* 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) { //递归边界,空树的深度为0 if(!pRoot) return 0; //递归求深度 return max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)) + 1; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-03-17
/* 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 deep=1; return deep+ max(TreeDepth(pRoot->left),TreeDepth(pRoot->right)); } };