leetcode 111(ツリーの最小深さ:ツリー遍歴)
6623 ワード
テーマ:二叉木を与えて、その最小深さを見つけます.
最小深度は、ルートノードから最近接リーフノードへの最短パス上のノード数です.
説明:リーフノードとは、サブノードがないノードを指します.
例:所与のツリー[3,9,20,null,null,15,7]出力最小深さ2
問題解:この問題はDFSアルゴリズムを使用する場合、結果を出すには完全な木を遍歴する必要があります.BFSアルゴリズムを使用すると、最初の葉のノードの深さが結果になります.
BFSコード
最小深度は、ルートノードから最近接リーフノードへの最短パス上のノード数です.
説明:リーフノードとは、サブノードがないノードを指します.
例:所与のツリー[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;
}
}