Swift-判断二叉树是否为平衡二叉树

题目:输入一棵二叉树的根结点,判断该树是不是平衡二叉树。如果某二叉树中任意结点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。例如,下图中的二叉树就是一棵平衡二叉树.


Swift-判断二叉树是否为平衡二叉树_第1张图片
二叉平衡树.jpg

最简单的解法是遍历每个节点左右节点深度,进行对比:

`
func isBalanceTree(rootNode:TreeNode?) -> Bool {
if rootNode == nil {
return true
}
let leftDepth:Int = treeMaxDepth(rootNode: rootNode?.leftChild)
let rightDepth:Int = treeMaxDepth(rootNode: rootNode?.rightChild)

    let diff:Int = leftDepth - rightDepth
    if diff > 1 || diff < -1 {
        return false
    }
    return isBalanceTree(rootNode: rootNode?.leftChild) && isBalanceTree(rootNode: rootNode?.rightChild)
}
`

上述解法不够高效,我们可以每次遍历的时候记录一下深度:

`

func isBalanceTreeOnce(rootNode:TreeNode?,depth:inout Int) -> Bool {
    if rootNode == nil {
        depth = 0
        return true
    }
    var leftDepth:Int = 0
    var rightDepth:Int = 0
    if isBalanceTreeOnce(rootNode: rootNode?.leftChild, depth: &leftDepth) && isBalanceTreeOnce(rootNode: rootNode?.rightChild, depth: &rightDepth) {
        let diff:Int = leftDepth - rightDepth
        if diff <= 1 && diff >= -1 {
            depth = leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1
            return true
        }
    }
    return false
}

func isBalancedTree(rootNode:TreeNode?) -> Bool {
    var depth:Int = 0
    return isBalanceTreeOnce(rootNode: rootNode, depth: &depth)
}`

测试代码:

`
var isBalance:Bool = binaryTreePath.isBalanceTree(rootNode: preRootNode)
print("FlyElephant-(depthData)二叉平衡树--(isBalance)")

var isBalance2:Bool = binaryTreePath.isBalancedTree(rootNode: preRootNode)
print("FlyElephant-(depthData)二叉平衡树--(isBalance2)")`

你可能感兴趣的:(Swift-判断二叉树是否为平衡二叉树)