104. Maximum Depth of Binary Tre

2018-01-26  本文已影响0人  caisense

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

思路:依然是层遍历,每到一层depth+1.

int maxDepth(TreeNode* root) {
    queue<TreeNode*> q;
    int depth = 0;  //深度统计,每到新一层+1
    if (!root) return 0;
    q.push(root);
    while (!q.empty()) {  //每层
        depth++;  //深度+1
        int size = q.size();
        for (int i = 0; i < size; i++) {
            auto tmp = q.front();
            q.pop();
            if (tmp->left) q.push(tmp->left);
            if (tmp->right ) q.push(tmp->right);
        }
    }
    return depth;
}
上一篇 下一篇

猜你喜欢

热点阅读