美文网首页
104. Maximum Depth of Binary Tre

104. Maximum Depth of Binary Tre

作者: caisense | 来源:发表于2018-01-26 22:30 被阅读0次

    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;
    }
    

    相关文章

      网友评论

          本文标题:104. Maximum Depth of Binary Tre

          本文链接:https://www.haomeiwen.com/subject/wycgaxtx.html