题目:
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.
提示:
此题的主要思想是DFS,其他没什么好说的。
代码:
我的代码是这样写的:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int maxDepth(TreeNode* root) { if (root == NULL) return 0; int sum = 1; int left_length = maxDepth(root->left); int right_length = maxDepth(root->right); return (left_length > right_length) ? (sum += left_length) : (sum += right_length); } };
虽然执行速度不慢,但是感觉写的很不简洁。后来在LeetCode的论坛中看到下述简洁的写法:
class Solution { public: int maxDepth(TreeNode* root) { if(!root) return 0; return max(maxDepth(root->left) + 1, maxDepth(root->right) + 1); } };
感觉比我的要好多了。