• 平衡二叉树


    题目:

    一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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 
    代码:
    type Node struct {
    	Left *Node
    	Rigth *Node
    	Value int64
    }
    
    func IsBlanceTree(root *Node) bool {
    	if root == nil {
    		return true
    	}
    
    	if !IsBlanceTree(root.Left) || !IsBlanceTree(root.Rigth) {
    		return false
    	}
    
    	lHight := GetMaxDeep(root.Left)
    	rHight := GetMaxDeep(root.Rigth)
    	
    	if Abs(lHight - rHight) > 1 {
    		return false
    	}
    
    	return true
    }
    
    func GetMaxDeep(root *Node) int {
    	if root == nil {
    		return 0
    	}
    
    	return Max(GetMaxDeep(root.Left), GetMaxDeep(root.Rigth)) + 1
    }
    
    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
    }
    

      地址:https://mp.weixin.qq.com/s/hBRfb3LpqDrB-I0mrPJmIA

  • 相关阅读:
    消除QQ表情小游戏
    图片排序
    自定义字体
    随机图片滚动
    生成500个0-1000的随机数&&数组查找—小练习
    文字搬运
    查找 替换
    BeginInvoke和EndInvoke方法
    MVC HtmlHelper用法大全
    30分钟LINQ教程 【转载】
  • 原文地址:https://www.cnblogs.com/smallleiit/p/13738167.html
Copyright © 2020-2023  润新知