104. Maximum Depth of Binary Tree
Binary tree, level order traversal
1.問題
給予一個binary tree, 找出最大的深度
最大的深度是指可到最遠的leaf node的子樹的長度
Note: leaf是指沒有children的node

2.想法
提問
確認題意
function header, parameter
test input
說明想法
最底層(NULL)視為-1層, 以此類推
測試計算複雜度
3.程式碼
/**
* 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) {
return 0;
}
return findDepth(root);
}
private:
int findDepth(TreeNode* root) {
if (!root) {
return 0;
}
return max(findDepth(root->left), findDepth(root->right)) + 1;
}
};
4.Performance

Previous103. Binary Tree Zigzag Level Order TraversalNext105. Construct Binary Tree from Preorder and Inorder Traversal
Last updated