简单深度优先

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例: 给定二叉树 [3,9,20,null,null,15,7], 3
/ \
9 20
/ \
15 7 最大深度就是3

递归解法

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. int maxDepth(TreeNode* root) {
  15. if(root == nullptr) return 0;
  16. return max(maxDepth(root->left),maxDepth(root->right)) + 1;
  17. }
  18. };

这里需要注意的是max函数的返回值是个左值,不能直接++然后返回。
时间复杂度O(n)
空间复杂度O(height) 递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。

BFS

  1. class Solution {
  2. public:
  3. int maxDepth(TreeNode* root) {
  4. if(root == nullptr) return 0;
  5. queue<TreeNode*> q;q.push(root);
  6. int count = 0;
  7. while(!q.empty()){
  8. count++;
  9. int size = q.size();
  10. for(int i=0;i<size;i++){
  11. TreeNode* node = q.front();q.pop();
  12. if(node->left != nullptr){
  13. q.push(node->left);
  14. }
  15. if(node->right != nullptr){
  16. q.push(node->right);
  17. }
  18. }
  19. }
  20. return count;
  21. }
  22. };

改装一下BFS算法,让每次遍历的时候遍历一层就好。