代码随想录打卡 Day17

110.平衡二叉树

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isBalanced(root *TreeNode) bool {
    res := getHight(root)
    if res == -1{
        return false
    }
    return true
}

func getHight(root *TreeNode) int {
    if root == nil{
        return 0
    }
    l , r := getHight(root.Left) , getHight(root.Right)
    if(l == -1 || r == -1){
        return -1 
    }
    if(l - r > 1 || r - l > 1){
        return -1
    }
    return max(l , r) + 1
}

func max(a int, b int) int {
    if a > b{
        return a
    }
    return b
}

257. 二叉树的所有路径

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func binaryTreePaths(root *TreeNode) []string {
    var res []string
    if root == nil{
        return res
    }

    var backAl func(root *TreeNode , s string)
    backAl = func(root *TreeNode , s string){
        if root.Right == nil && root.Left == nil{
            a := s + strconv.Itoa(root.Val)
            res = append(res , a)
            return
        }
        s = s + strconv.Itoa(root.Val) + "->"
        if root.Left != nil{
            backAl(root.Left , s)
        }
        if root.Right != nil{
            backAl(root.Right , s)
        }
    }
    backAl(root,"")
    return res
}

404.左叶子之和

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumOfLeftLeaves(root *TreeNode) int {
    sum := 0
    if root == nil{
        return sum
    }
    var backAl func(root *TreeNode) 
    backAl = func(root *TreeNode) {
         if (root.Left == nil && root.Right == nil){
             return
         }
        if(root.Left != nil && root.Left.Left == nil && root.Left.Right == nil){
            sum = sum + root.Left.Val
        }
        if root.Left != nil{
            backAl(root.Left)
        }
        if root.Right != nil{
            backAl(root.Right)
        }
    }
    backAl(root)
    return sum
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值