题解 | #判断是不是平衡二叉树#

判断是不是平衡二叉树

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

package main

import . "nc_tools"

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param pRoot TreeNode类
 * @return bool布尔型
 */
func IsBalanced_Solution(pRoot *TreeNode) bool {
	// write code here
	if pRoot == nil {
		return true
	}

	return getDepthDiff(pRoot) != -1
}

func getDepthDiff(pRoot *TreeNode) int {
	if pRoot == nil {
		return 0
	}

	l := getDepthDiff(pRoot.Left)
	if l < 0 {
		return -1
	}
	r := getDepthDiff(pRoot.Right)
	if r < 0 {
		return -1
	}

	if abs(l, r) > 1 {
		return -1
	}

	return max(l, r) + 1
}

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

	return b - a
}

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

	return b
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务