[leetcode]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.

分析:
要得出二叉樹中所有從根到葉子節點路徑中,經過結點最少路徑上的節點數。採用二叉樹的層序遍歷思想,每遍歷一層,高度加一,只要遇到葉子節點,就終止,並返回當前層數。
代碼:

class Solution {
public:
    int minDepth(TreeNode* root) {
        deque<TreeNode*> store;

        int left_num;
        int res = 0;
        if(!root)
            return res;
        store.push_back(root);
        while(!store.empty()) {
            res++;
            vector<int> res_t;
            left_num = store.size(); 
            while(left_num-- > 0) {
                const TreeNode* tmp = store.front();
                if(!tmp->left&&!tmp->right)
                    return res;
                store.pop_front();
                res_t.push_back(tmp->val);
                if(tmp->left)
                    store.push_back(tmp->left);
                if(tmp->right)
                    store.push_back(tmp->right);
            }
        }

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