104. Maximum Depth of Binary Tree
Food for thought
確定葉節點(leaf node)回傳的深度值為1;
參考鄉民解答,發現可以再精簡成一行,長見識
[WRONG] C++ Solution
int maxDepth(TreeNode* root)
{
if (!root) return 0;
int left_depth = 0;
int right_depth = 0;
if (root->left) left_depth = maxDepth(root->left) + 1;
if (root->right) right_depth = maxDepth(root->right) + 1;
return left_depth > right_depth ? left_depth : right_depth;
}
// 原始作答,明顯錯誤為未確認當root為leaf node時(i.e. left and right are NULL),要回傳1
C++ Solution
int maxDepth(TreeNode* root)
{
if (!root) return 0;
int left_depth = 1;
int right_depth = 1;
if (root->left) left_depth = maxDepth(root->left) + 1;
if (root->right) right_depth = maxDepth(root->right) + 1;
return left_depth > right_depth ? left_depth : right_depth;
// one line solution, clean code
// return root == NULL ? 0 : max(maxDepth(root->left), maxDepth(root->right)) + 1;
}