leetcode 104 二叉树的最大深度

99 阅读1分钟

leetcode 104 二叉树的最大深度

DFS or BFS

思路

  1. 深度优先遍历,每层递归返回时,取左右子树最大值 + 1;

or

  1. 层序遍历,某一层count ++;

代码

DFS:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;
        return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};

BFS:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        queue<TreeNode*> que;
        if(root != NULL) que.push(root);
        int count = 0;
        while(!que.empty()) {
            int size = que.size();
            for(int i = 0; i < size; i++) {
                TreeNode* node = que.front();
                que.pop();
                if(node->left) que.push(node->left);
                if(node->right) que.push(node->right);
            }
            count++;
        }
        return count;
    }
};