首页 > 其他 > 详细

是否是平衡的二叉树

时间:2020-07-01 19:56:08      阅读:50      评论:0      收藏:0      [点我收藏+]

解题思路:

在理解题意以后,我们需要先分解下问题。首先要先获取节点高度,然后再再进行比对判断,判断每一个节点左右子树的高度差的绝对值是否超过1。

我们需要了解如何遍历二叉树,这样才能知道树的高度。还要了解递归的思想可以让代码逻辑更加清晰。

type TreeNode struct {
    left *TreeNode
    right *TreeNode
    value int
}

func max(a,b int) int {
    if a > b {
        return a
    }
    return b
}
func abs(a int) int {
    if a >= 0 {
        return a
    }
    return -a
}
func getHeight(root *TreeNode) int {
    if root == nil {
        return 0
    }
    return 1 + max(getHeight(root.left),getHeight(root.right))
}
func isBalanced(root *TreeNode) bool {
    if root == nil {
        return true
    }
    if abs(getHeight(root.left)-getHeight(root.right)) > 1 {
        return false
    }
    return isBalaned(root.left) && isBalaned(root.right)
}

  

 

原文地址:https://studygolang.com/articles/29553#reply0

是否是平衡的二叉树

原文:https://www.cnblogs.com/smallleiit/p/13220638.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!