当前位置:网站首页>【LeetCode】111. Minimum depth of binary tree (2 brushes of wrong questions)

【LeetCode】111. Minimum depth of binary tree (2 brushes of wrong questions)

2022-07-05 02:20:00 Kaimar

0
1

  • Ideas
    Want to use queues , Use the method of sequence traversal to judge , Once there is a leaf node, exit .( Iterative method )
    Refer to the explanation of the question
    Using recursive method , First, clarify the three elements of recursion
    Recursive parameters and return values : The parameter is the current node , The return value is the minimum depth of the current node as the root node ;
    The termination condition of recursion : When there is a leaf node, it terminates ;
    Recursive single-layer logic : First, specify what traversal method to use , Here we use post order traversal ( Because to compare Recursively returns Later results ); secondly , Use the smaller depth value in the left and right subtrees .
//  Iterative method 
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */
func minDepth(root *TreeNode) int {
    
    if root == nil {
    
        return 0
    }
    queue := []*TreeNode{
    root}
    res := 0
    for len(queue) > 0 {
    
        curLen := len(queue)
        res++
        for i := 0; i < curLen; i++ {
    	//  Traverse the current layer 
            node := queue[0]
            queue = queue[1:]
            if node.Left != nil {
    
                queue = append(queue, node.Left)
            }
            if node.Right != nil {
    
                queue = append(queue, node.Right)
            }
            if node.Left == nil && node.Right == nil {
    
                return res
            }
        }
    }
    return res
}

//  Recursive method 
func min(a, b int) int {
    
    if a > b {
    
        return b
    }
    return a
}
func minDepth(root *TreeNode) int {
    
    if root == nil {
    
        return 0
    }
    //  Left 
    left := minDepth(root.Left)
    //  Right 
    right := minDepth(root.Right)
    //  in 
    //  One of the two cases is empty , What needs to be returned is the minimum depth on the side that is not empty 
    if root.Left != nil && root.Right == nil {
    
        return 1 + left
    }
    if root.Left == nil && root.Right != nil {
    
        return 1 + right
    }
    //  All is empty 
    return 1 + min(left, right)
}

4

原网站

版权声明
本文为[Kaimar]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140933283889.html