Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

111. 二叉树的最小深度 #52

Open
yankewei opened this issue Aug 22, 2020 · 2 comments
Open

111. 二叉树的最小深度 #52

yankewei opened this issue Aug 22, 2020 · 2 comments
Labels
广度优先搜索 题目包含广度优先搜索解法 题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最小深度  2.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree

@yankewei yankewei added 简单 题目难度为简单 深度优先搜索 题目包含深度优先搜索解法 题目类型为树结构 labels Aug 22, 2020
@yankewei
Copy link
Owner Author

深度优先搜索

深度优先搜索就很简单了,鉴于这种树的性质,经常用递归来求解,对于这个题,我们分别求出左右子树的最小深度就可以了。

type TreeNode struct {
    Val   int
    Left  *TreeNode
    Right *TreeNode
}
func minDepth(root *TreeNode) int {
    if root == nil {
        return 0
    }
    if root.Left == nil && root.Right == nil {
        return 1
    }
    minD := math.MaxInt32
    if root.Left != nil {
        minD = min(minDepth(root.Left), minD)
    }
    if root.Right != nil {
        minD = min(minDepth(root.Right), minD)
    }
    return minD + 1
}

func min(x, y int) int {
    if x < y {
        return x
    }
    return y
}

@yankewei
Copy link
Owner Author

广度优先搜索

深度优先搜索有一个问题,就是我必须要递归到底部,去比较左右两个子树的深度。如果我们用广度优先搜索,当找到一个叶子节点,我们直接返回当前深度即可,没有必要再去搜索其它的子树。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func minDepth(root *TreeNode) int {
    var ret int
    if root == nil {
	return ret
    }
    deQueue := []*TreeNode{root}
    tmpQueue := []*TreeNode{}

    for len(deQueue) != 0 {
	if deQueue[0].Left == nil && deQueue[0].Right == nil {
	    ret++
	    break
	}
	if deQueue[0].Left != nil {
	    tmpQueue = append(tmpQueue, deQueue[0].Left)
	}
	if deQueue[0].Right != nil {
	    tmpQueue = append(tmpQueue, deQueue[0].Right)
	}
	deQueue = deQueue[1:]
	if len(deQueue) == 0 {
	    ret++
	    deQueue = tmpQueue
	    tmpQueue = tmpQueue[len(tmpQueue):]
	}
    }
    return ret
}

@yankewei yankewei added the 广度优先搜索 题目包含广度优先搜索解法 label Aug 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
广度优先搜索 题目包含广度优先搜索解法 题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant