zoukankan      html  css  js  c++  java
  • 平衡二叉树

    题目:

    一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过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

  • 相关阅读:
    流程控制语句
    第一周考点
    8.6
    8.5
    自用论文排版组合 = LyX2.2.2 + TeXLive2016
    解析几何图解
    概率论与数理统计图解.tex
    硕士研究生入学考试复试试卷答案.tex
    概率论与数理统计图解
    一月7日
  • 原文地址:https://www.cnblogs.com/smallleiit/p/13738167.html
Copyright © 2011-2022 走看看