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.

BST中深度的問題,我們可以遞歸(DFS),也可以迭代解決(BFS),我習慣性用迭代,主要是用習慣了。需要注意的是,判斷條件是葉子節點,不是左右子樹,代碼如下:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==NULL) return 0;
        //if(root->left&&!root->right||!root->left&&root->right) return 2;
        queue<TreeNode*> A;
        A.push(root);A.push(NULL);
        int depth=1;
        while(!A.empty()){
            auto B=A.front();
            if(B==NULL){
                depth++;A.pop();
            }
            else{
                if(!B->left&&!B->right) return depth;
                else {
                    if(B->left) A.push(B->left);
                    if(B->right) A.push(B->right);
                    A.pop();
                    if(A.front()==NULL) A.push(NULL);
                }
            }
        }
        return depth;
    }
};

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