题目

二叉树结构如下:

//Definition for a binary tree node.
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };

题解

详细题解可参见#104题解

1. 递归法

  • 时间复杂度$O(N)$
  • 空间复杂度$O(N)$
class Solution {//两个方法。1. 递归法
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        //递归取左右子树中大的那个,注意要+1
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

2. 非递归法(BFS)

  • 时间复杂度$O(N)$
  • 空间复杂度$O(1)$
class Solution {//两个方法。2. 队列迭代法
public:
    int maxDepth(TreeNode* root) {
        if(!root) return 0;
        int level = 0;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            for(int i = q.size(); i>0; --i){
                auto cur = q.front(); q.pop();
                if(cur->left) q.push(cur->left);
                if(cur->right) q.push(cur->right);
            }
            level++;
        }
        return level;
    }
};