题目:Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
和求树的最小深度问题一样,存在着自底向上和自顶向下两种解法
解析1:自底向上,代码如下:
// 递归法,时间复杂度 O(n),空间复杂度 O(logn) // 自底向上,从叶节点开始计算树的最大深度 class Solution { public: int maxDepth(TreeNode* root) { if (!root) return 0; return max(maxDepth(root -> left), maxDepth(root -> right)) + 1; } };解析2:自顶向下,代码如下:
// 迭代法,时间复杂度 O(N), 空间复杂度 O(logn) // 自顶向下,从根节点开始计算树的最大深度 class Solution public: int maxDepth(TreeNode* root) { if (!root) return 0; int result = 0; stack<pair<TreeNode*, int>> s; s.push(make_pair(root, 1)); while (!s.empty()) { auto p = s.top().first; auto depth = s.top().second; s.pop(); if (!p -> left && !p -> right) result = max(result, depth); if (p -> left) s.push(p -> left, depth + 1); if (p -> righth) s.push(p -> right, depth + 1); } return result; } };