問題:バイナリツリーが与えられた場合、その最小深度を見つけます。
最小深度は、ルートノードから最も近いリーフノードまでの最短パス上のノードの数です。
説明:葉ノードは、子ノードのないノードを指します。
例:
バイナリツリー[3,9,20、null、null、15,7]の
出力の最小深度2
解決策:この問題にDFSアルゴリズムを使用する場合、ツリー全体をトラバースして結果を取得する必要があります。BFSアルゴリズムを使用する場合、最初に検出されたリーフノードの深さが結果になります。
BFSコード
class Solution {
//class nodeDepth用于保存每个结点的深度,是整个BFS算法的关键
class nodeDepth{
TreeNode node;
int depth;
public nodeDepth(TreeNode node, int depth) {
this.node = node;
this.depth = depth;
}
}
public int minDepth(TreeNode root) {
if(root==null)
return 0;
Queue<nodeDepth> BFS=new LinkedList<>();
BFS.offer(new nodeDepth(root,1));
while(!BFS.isEmpty()){
nodeDepth peek=BFS.poll();
if(peek.node.left==null&&peek.node.right==null)
return peek.depth;
if(peek.node.left!=null)
BFS.offer(new nodeDepth(peek.node.left, peek.depth+1));
if(peek.node.right!=null)
BFS.offer(new nodeDepth(peek.node.right, peek.depth+1));
}
return -1;
}
}