111. 二叉树的最小深度-E

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/scylhy/article/details/87907382

111. 二叉树的最小深度-E

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

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

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

示例:

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

    3
   / \
  9  20
 /     \
15      7

返回它的最小深度 2.

  • 分析
    比最大深度那个稍微复杂一点,因为只有单子树的时候,需要另加判断,仍是深度遍历。
  • code
/**
 * 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
    }
    a:=minDepth(root.Left)
    b:=minDepth(root.Right)
    if root.Left==nil||root.Left!=nil&&root.Right!=nil&&a>b{
        a=b
    }
    return a+1
}
  • code:按层遍历
package main

import (
	"fmt"
)

type TreeNode struct {
  Val int
  Left *TreeNode
  Right *TreeNode
}
type stack struct{
	Val []*TreeNode
}
func(s*stack)push(v *TreeNode){
	s.Val=append(s.Val,v)
}
func(s*stack)pop()*TreeNode{
	if len(s.Val)==0{
		return nil
	}
	a:=s.Val[0]
	s.Val=s.Val[1:]
	return a
}
func(s*stack)peek()*TreeNode{
	if len(s.Val)==0{
		return nil
	}
	return s.Val[len(s.Val)-1]

}
func(s*stack)size()int{
	return len(s.Val)
}
func minDepth(root *TreeNode) int {
	if root==nil{
		return 0
	}
	var sk stack
	sk.push(root)
	mostRight:=root
	height:=1
	for sk.size()>0{
		p:=sk.pop()
		if p.Left==nil&&p.Right==nil{
			break
		}
		if p.Left!=nil{
			sk.push(p.Left)
		}
		if p.Right!=nil{
			sk.push(p.Right)
		}
		if mostRight==p{
			height++;mostRight=sk.peek()
		}
	}
	return height
}
func main(){

	var t1,t2,t3,t4,t5,t6 TreeNode
	t1.Val=3;t2.Val=9;t3.Val=20;t4.Val=15;t5.Val=7
	t1.Left=&t2;t1.Right=&t3;t3.Left=&t4;t3.Right=&t5
	fmt.Println(minDepth(&t1))

	return



	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=5;t2.Val=14;t3.Val=1
	t1.Left=&t2;t2.Left=&t3
	fmt.Println(minDepth(&t1))
	t1.Val=2;t1.Left=&t2;t1.Right=&t3
	t2.Val=1;t3.Val=3
	fmt.Println(minDepth(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t4.Val=4;t5.Val=5;t6.Val=6
	t5.Left=&t1;t1.Left=nil;t1.Right=nil
	t5.Right=&t4;t4.Left=&t3;t4.Right=&t6
	fmt.Println(minDepth(&t5))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=10;t2.Val=5;t3.Val=15;t4.Val=6;t5.Val=20
	t1.Left=&t2;t1.Right=&t3;t3.Left=&t4;t3.Right=&t5
	fmt.Println(minDepth(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=1
	fmt.Println(minDepth(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	fmt.Println(minDepth(nil))
}

猜你喜欢

转载自blog.csdn.net/scylhy/article/details/87907382