https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
class Solution { public: void TreeDepthHelper(TreeNode* pRoot, int curr, int& max) { if (pRoot == nullptr) { if (max < curr) max = curr; return; } TreeDepthHelper(pRoot->left, curr + 1, max); TreeDepthHelper(pRoot->right, curr + 1, max); } int TreeDepth(TreeNode* pRoot) { if (pRoot == nullptr) return 0; int depth = 0;//遍历到当前位置时,最大的值 int max = 0;//返回值 TreeDepthHelper(pRoot, depth, max); return max; } };
class Solution { public: int TreeDepth(TreeNode* pRoot) { if (pRoot == nullptr) { return 0; } return 1 + max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)); //1+左子树中最大的数字或者右子树最大的数字 } };
层序遍历,有多少层就是多高
class Solution { public: int TreeDepth(TreeNode* pRoot) { if (pRoot == nullptr) return 0; queue<TreeNode*> q; q.push(pRoot); int depth = 0; while (!q.empty()) { int size = q.size(); depth++; for (int i = 0; i < size; i++) { TreeNode* curr = q.front(); q.pop(); if (curr->left) q.push(curr->left); if (curr->right) q.push(curr->right); } } return depth; } };