代码随想录day 16

详细布置

104.二叉树的最大深度 (优先掌握递归)

什么是深度,什么是高度,如何求深度,如何求高度,这里有关系到二叉树的遍历方式。

大家 要先看视频讲解,就知道以上我说的内容了,很多录友刷过这道题,但理解的还不够。

题目链接/文章讲解/视频讲解: 代码随想录

/**

 * Definition for a binary tree node.

 * type TreeNode struct {

 *     Val int

 *     Left *TreeNode

 *     Right *TreeNode

 * }

 */

func maxDepth(root *TreeNode) int {

      if root == nil {        // 如果为空返回0 

          return 0 

      }else{

          leftmax := maxDepth(root.Left)      // 左子树最大深度

          rightmax := maxDepth(root.Right)    // 右子树最大深度

          height := (max(leftmax,rightmax))+1    //左右子树里最大深度再加1 

          return height 

      }

     

}

func max(a,b int) int {

    if a > b {

        return a 

    }else {

        return b 

    }

}

111.二叉树的最小深度 (优先掌握递归)

先看视频讲解,和最大深度 看似差不多,其实 差距还挺大,有坑。

题目链接/文章讲解/视频讲解:代码随想录

代码如下

/**

 * Definition for a binary tree node.

 * type TreeNode struct {

 *     Val int

 *     Left *TreeNode

 *     Right *TreeNode

 * }

 */

func minDepth(root *TreeNode) int {

       if root == nil {                                      //如果跟节点为空 返回0 

           return 0

       }

       leftmin := minDepth(root.Left)            // 求出左右子树的最小深度

       rightmin := minDepth(root.Right)

       if root.Left == nil || root.Right == nil {     //如果左右子树有一个为空则返回的深度是另一个子树                                                                       //深度+1

          

           return leftmin + rightmin + 1

       }else {

           return (min(leftmin,rightmin)+1)         //两个子树都不为空,返回最小子树深度+1

       }

}



 

func min(a,b int) int {

    if a < b {

        return a 

    }else {

        return b 

    }

}

222.完全二叉树的节点个数(优先掌握递归)

需要了解,普通二叉树 怎么求,完全二叉树又怎么求

题目链接/文章讲解/视频讲解: 代码随想录

/**

 * Definition for a binary tree node.

 * type TreeNode struct {

 *     Val int

 *     Left *TreeNode

 *     Right *TreeNode

 * }

 */

func countNodes(root *TreeNode) int {

          if root == nil {                                         

              return 0 

          }

          res := 1 

          if root.Left != nil {

              res += countNodes(root.Left)

          }

          if root.Right != nil {

              res += countNodes(root.Right)

          }

          return res 

}

感想 :题目不算太难,最近刚学了go语言,用go写一写代码。把之前落下来的补一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值