110. 平衡二叉树-E

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/scylhy/article/details/87912933

110. 平衡二叉树-E

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
 /     \
15      7

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

      1
     / \
    2   2
   /     \
  3       3
 /         \
4           4

返回 false 。

  • 分析
    就是获取树的高度,判断左右子树高度差是否满足要求
  • code2 用-1表示不平衡,更简洁点
package main
import (
	"fmt"
)
type TreeNode struct {
  Val int
  Left *TreeNode
  Right *TreeNode
}
//用-1表示unbalanced
func BST(root*TreeNode,)int {
	if root == nil {
		return 0
	}
	a:=BST(root.Left)
	if a==-1{
		return -1
	}
	b:=BST(root.Right)
	if b==-1||a-b>1||b-a>1{ //判断左右子树高度差是否满足
		return -1
	}
	if a<b{ //返回树的高度
		a=b
	}
	return a+1
}
func isBalanced(root *TreeNode) bool {
	if BST(root)==-1{
		return false
	}
	return true
}
func main(){

	var t1,t2,t3,t4,t5,t6 TreeNode
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=5;t2.Val=14;t3.Val=1
	t1.Left=&t2;t2.Left=&t3
	fmt.Println(isBalanced(&t1))
	t1.Val=2;t1.Left=&t2;t1.Right=&t3
	t2.Val=1;t3.Val=3
	fmt.Println(isBalanced(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t4.Val=4;t5.Val=5;t6.Val=6
	t5.Left=&t1;t1.Left=nil;t1.Right=nil
	t5.Right=&t4;t4.Left=&t3;t4.Right=&t6
	fmt.Println(isBalanced(&t5))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=10;t2.Val=5;t3.Val=15;t4.Val=6;t5.Val=20
	t1.Left=&t2;t1.Right=&t3;t3.Left=&t4;t3.Right=&t5
	fmt.Println(isBalanced(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=1
	fmt.Println(isBalanced(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	fmt.Println(isBalanced(&t1))
}
  • code1 用go的多返回值
package main
import (
	"fmt"
)
type TreeNode struct {
  Val int
  Left *TreeNode
  Right *TreeNode
}
func BST(root*TreeNode,)(int,bool) {
	if root == nil {
		return 0,true
	}
	a,b:=BST(root.Left)
	if !b{
		return 0,false
	}
	c,d:=BST(root.Right)
	if !d{
		return 0,false
	}
	if a-c>1||c-a>1{ //判断左右子树高度差是否满足
		return 0,false
	}
	if a<c{ //返回树的高度
		a=c
	}
	return a+1,true
}

func isBalanced(root *TreeNode) bool {
	_,b:=BST(root)
	return b

}
func main(){

	var t1,t2,t3,t4,t5,t6 TreeNode
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=5;t2.Val=14;t3.Val=1
	t1.Left=&t2;t2.Left=&t3
	fmt.Println(isBalanced(&t1))
	t1.Val=2;t1.Left=&t2;t1.Right=&t3
	t2.Val=1;t3.Val=3
	fmt.Println(isBalanced(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t4.Val=4;t5.Val=5;t6.Val=6
	t5.Left=&t1;t1.Left=nil;t1.Right=nil
	t5.Right=&t4;t4.Left=&t3;t4.Right=&t6
	fmt.Println(isBalanced(&t5))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=10;t2.Val=5;t3.Val=15;t4.Val=6;t5.Val=20
	t1.Left=&t2;t1.Right=&t3;t3.Left=&t4;t3.Right=&t5
	fmt.Println(isBalanced(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	t1.Val=1
	fmt.Println(isBalanced(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1;t6=t1
	fmt.Println(isBalanced(&t1))
}

猜你喜欢

转载自blog.csdn.net/scylhy/article/details/87912933