111. Minimum Depth of Binary Tree

来源:互联网 发布:手机淘宝尺寸怎么设置 编辑:程序博客网 时间:2024/06/16 21:24

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

BFS, C++, 8ms, Beats 99.94% submissions

/** * 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 minDepth(TreeNode* root) {        if (root == NULL) return 0;        queue<TreeNode*> qt;        qt.push(root);        int min = 0;        while (!qt.empty())         {            min++;            for (int i=0,n=qt.size(); i<n;i++)             {                TreeNode* cur_node = qt.front();                if (cur_node->left) qt.push(cur_node->left);                if (cur_node->right) qt.push(cur_node->right);                qt.pop();                if (!cur_node->left && !cur_node->right) return min;            }        }        return min;    }};

递归

/** * 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 minDepth(TreeNode* root) {        if(!root) return 0;        if(!root->left)            return minDepth(root->right)+1;        if(!root->right)            return minDepth(root->left)+1;        return 1+min(minDepth(root->left),minDepth(root->right));    }};


0 0
原创粉丝点击