[算法相關] Minimum Depth of Binary Tree

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.

如題,給定一個二叉樹確定其最小深度。

               

圖示二叉樹的最小深度爲三。代碼如下:

 

public class Solution {
public int minDepth(TreeNode root) {
    if (root == null)
        return 0;
    int depth = 1;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    TreeNode temp,magic = new TreeNode(0);
    queue.add(root);
    queue.add(magic);
    while(!queue.isEmpty()){
        temp = queue.poll();
        if(temp.equals(magic)){
            if(!queue.isEmpty()){
                depth++;
                queue.add(magic);
            }
            continue;
        }
        if(temp.left == null && temp.right == null)
            return depth;
        if(temp.left != null)
            queue.add(temp.left);
        if(temp.right != null)
            queue.add(temp.right);
    }
    return depth;
}
}

上述程序使用了層次遍歷的方法,運用了遍歷操作。不理解,這裏的層次遍歷是如何用的,並且二叉樹是如何與隊列相聯繫的。

 

To be  continue……


 

 

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