公式二叉树深度
0:二叉树结构
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
1:计算最大值
func max(x, y int) int {
if x > y {
return x
}
return y
}
2:计算高度
func height(root *TreeNode) int {
if root == nil {
return 0
}
return max(height(root.Left), height(root.Right)) + 1
}
3:计算高度差
func abs(x int) int {
if x < 0 {
return -1 * x
}
return x
}
例如:
二叉树最大深度
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
if root ==nil {
return 0
}
return max(maxDepth(root.Left),maxDepth(root.Right))+1
}
func max(a,b int) int{
if a>b {
return a
}
return b
}
平衡二叉树
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isBalanced(root *TreeNode) bool {
if root == nil{
return true
}
return abs(height(root.Left)-height(root.Right))<=1&&isBalanced(root.Left)&&isBalanced(root.Right)
}
func height(root *TreeNode) int{
if root==nil{
return 0
}
return max(height(root.Left),height(root.Right))+1
}
func max(a ,b int) int{
if a>b {
return a
}
return b
}
func abs(x int) int {
if x<0{
return -1*x
}
return x
}
具体题目具体分析,好孩子不要愣套公式