传送门
nowcoder
leetcode
题目描述
输入一棵二叉树,求该树的深度。
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
class Solution { public: int TreeDepth(TreeNode* pRoot) { if (pRoot == nullptr) return 0; int leftDepth = TreeDepth(pRoot->left); int rightDepth = TreeDepth(pRoot->right); return max(leftDepth, rightDepth) + 1; } };
class Solution { public: int TreeDepth(TreeNode* pRoot) { if (pRoot == nullptr) return 0;
queue<pair<TreeNode*, int>> que; que.push(make_pair(pRoot, 1)); int maxDepth = 1; while (!que.empty()) { TreeNode* curNode = que.front().first; int curDepth = que.front().second; que.pop(); if (curNode) { maxDepth = max(maxDepth, curDepth); que.push({ curNode->left, curDepth + 1 }); que.push({ curNode->right, curDepth + 1 }); } } return maxDepth; } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
class Solution { private: int depth = 0; int res = 0;
public: int calculateDepth(TreeNode* root) { traverse(root); return res; }
void traverse(TreeNode* root) { if (root == nullptr) { return; }
depth ++; res = std::max(res, depth); traverse(root->left); traverse(root->right); depth --; } };
class Solution { public: int calculateDepth(TreeNode* root) { if (root == nullptr) { return 0; }
int leftMax = calculateDepth(root->left); int rightMax = calculateDepth(root->right); return 1 + std::max(leftMax, rightMax); } };
|