leetcode 111: Minimum Depth of Binary Tree

问题描述:

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.

思路:

思路很简单,就是直接地按层遍历二叉树,然后发现叶节点就跳出即可。
但是一开始做得很糊涂,以为一个节点没有两个儿子就当做叶节点,折腾了好久才发现错误,而且这个错误在做Path Sum那题的时候也有这么一个折腾的过程,但当时没有记下,反而让错误思维固势。特此记录。

代码:

class Solution {   
public:
    int minDepth(TreeNode* root) {
        list<TreeNode*> nodelist;
        if (root == NULL) return 0;
        nodelist.push_back(root);

        int depth = 0;
        bool isbreak = false;    //is get from break
        while ((!nodelist.empty()) && (!isbreak))
        {
            int length = nodelist.size();
            for (int i = 0; i < length; i++)
            {
                TreeNode *now = *nodelist.begin();
                if ((now->left == NULL) && (now->right == NULL))     //determine if it is a leaf
                {
                    isbreak = true;   //find the leaf, set break signal
                    break;
                }
                if (now->left) nodelist.push_back(now->left);
                if (now->right) nodelist.push_back(now->right);
                nodelist.pop_front();
            }
            depth++;
        }
        return depth;
    }

};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章