#155 Minimum Depth of Binary Tree

来源:互联网 发布:python web 开发 编辑:程序博客网 时间:2024/04/30 15:23

题目描述:

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.

Example

Given a binary tree as follow:

  1 / \ 2   3   / \  4   5

The minimum depth is 2.

题目思路:

这题我还是用了bfs比较方便,用一个queue来记录从top到bottom的nodes,再用一个queue来记录相应nodes的level。当发现有node没有子树的时候,它的level就是我们所在的答案。

Mycode(AC = 76ms):

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /**     * @param root: The root of binary tree.     * @return: An integer     */    int minDepth(TreeNode *root) {        // write your code here        if (root == NULL) {            return 0;        }                // store the nodes from top to bottom        queue<TreeNode *> helper;        helper.push(root);        // store the level of each node        queue<int> levels;        levels.push(1);                int level;        while (!helper.empty()) {            // get the node and level from front of queue            TreeNode *node = helper.front();            helper.pop();            level = levels.front();            levels.pop();                        // if it is single node, then return level            if (!node->left && !node->right) {                return level;            }                        // push the left/right node into queue            if (node->left) {                helper.push(node->left);                levels.push(level + 1);            }            if (node->right) {                helper.push(node->right);                levels.push(level + 1);            }        }                return level;            }};


0 0
原创粉丝点击