Day 17 二叉树Part04

Day 17 二叉树Part04

110. 平衡二叉树 - 力扣(LeetCode)

分别计算左右子树的高度即可,

func isBalanced(root *TreeNode) bool {
    if root == nil {
        return true
    }
    var hight, l, r int

    var compare func (*TreeNode, int) int 
    compare = func (root *TreeNode, h int) int {
        if root == nil {
            return h
        }
        h++
        l, r = compare(root.Left, h), compare(root.Right, h)
        fmt.Println(l, r)
        if l == -1 || r == -1 { // 等于-1即不成立
            return -1
        }
        if balance(l, r) {
            return max(l, r)
        } else {
            return -1
        }
    }    
    return compare(root, hight) != -1
}

func balance(a, b int) bool { // 平衡条件
    return a - b < 2 && b - a < 2
}

func max(a, b int) int { // 返回最深的深度
    if a > b {
        return a
    }
    return b
}

257. 二叉树的所有路径 - 力扣(LeetCode)

基本也还是遍历,转换字符串稍稍麻烦点

var paths []string
func binaryTreePaths(root *TreeNode) []string {
    paths = []string{}
    constructPaths(root, "")
    return paths
}

func constructPaths(root *TreeNode, path string) {
    if root != nil {
        pathSB := path
        pathSB += strconv.Itoa(root.Val) // 整型转化为字符串
        if root.Left == nil && root.Right == nil {
            paths = append(paths, pathSB)
        } else {
            pathSB += "->"
            constructPaths(root.Left, pathSB)
            constructPaths(root.Right, pathSB)
        }
    }
}

404. 左叶子之和 - 力扣(LeetCode)

左叶子,不是左节点,这个有点小烦人

func sumOfLeftLeaves(root *TreeNode) int {
    var sum int
    var sonLeft func(root *TreeNode)
    sonLeft = func(root *TreeNode) {
        // fmt.Println(sum)
        if root.Left != nil {
            if root.Left.Left == nil && root.Left.Right == nil {
                sum += root.Left.Val
            }
            sonLeft(root.Left)
        }
        if root.Right != nil {
            sonLeft(root.Right)
        }
    } 
    sonLeft(root)
    return sum
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值