vault backup: 2022-07-05 09:55:27

This commit is contained in:
juan 2022-07-05 09:55:27 +08:00
parent e62c97e039
commit e1ca38b6aa

View file

@ -56,12 +56,38 @@ BFS way:
Simply log the level in each while iteration.
DFS way: (Popular)
Use recursion
Use recursion:
- Base Case:
- root == nullptr: return 0;
- maxDepth(root) = max(maxDepth(root->left), maxDepth(root->right))
### Solution
DFS Recursion:
```cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
// DFS
if (!root) {
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
```
BFS: