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

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