Leetcode 104 Maximum Depth of Binary Tree

来源:互联网 发布:文明6 简体中文 mac版 编辑:程序博客网 时间:2024/05/21 19:17

Q:

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.


A:

/**

 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        int height = 0,rowCount = 1;
        
        if(root == NULL){
            return 0;
        }


        queue<TreeNode*> queue;
        queue.push(root);


        while(!queue.empty()){
            TreeNode *node = queue.front();
            queue.pop();
            rowCount --;
            
            if(node->left){
                queue.push(node->left);
            }
            if(node->right){
                queue.push(node->right);
            }


            if(rowCount == 0){
                height++;
                rowCount = queue.size();
            }
        }
        return height;        
    }
};
原创粉丝点击