leetcode111 (minimum depth of binary tree: binary tree traversal)

Problem: Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes on the shortest path from the root node to the nearest leaf node.

Explanation: A leaf node refers to a node without child nodes.

Example:
Given a binary tree [3,9,20,null,null,15,7]
output minimum depth 2

Solution: If you use the DFS algorithm for this problem, you need to traverse the entire tree to get the result. If you use the BFS algorithm, the depth of the first leaf node encountered is the result.

BFS code

 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;
            }
        }

Guess you like

Origin blog.csdn.net/CY2333333/article/details/108144507