算法笨方法之公式二叉树(Go)

公式二叉树深度

0:二叉树结构

type TreeNode struct {
      Val int
      Left *TreeNode
      Right *TreeNode
  }

1:计算最大值

func max(x, y int) int {
    if x > y {
        return x
    }
    return y
}

2:计算高度

func height(root *TreeNode) int {
    if root == nil {
        return 0
    }
    return max(height(root.Left), height(root.Right)) + 1
}

3:计算高度差

func abs(x int) int {
    if x < 0 {
        return -1 * x
    }
    return x
}

例如:

二叉树最大深度

* type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    if root ==nil {
        return 0
    }
    return max(maxDepth(root.Left),maxDepth(root.Right))+1
}
func max(a,b int) int{
    if a>b {
        return a
    }
    return b
}

平衡二叉树

 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */


func isBalanced(root *TreeNode) bool {
    if root == nil{
        return true
    }
    return abs(height(root.Left)-height(root.Right))<=1&&isBalanced(root.Left)&&isBalanced(root.Right)
}
func height(root *TreeNode) int{
    if root==nil{
        return 0
    }
    return max(height(root.Left),height(root.Right))+1
}
func max(a ,b int) int{
    if a>b {
        return a
    }
    return b
}
func abs(x int) int {
    if x<0{
        return -1*x
    } 
    return x
}

具体题目具体分析,好孩子不要愣套公式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值