zoukankan      html  css  js  c++  java
  • 剑指offer-平衡二叉树

    题目描述:输入一棵二叉树,判断该二叉树是否是平衡二叉树。

    思路:最长路径和最短路径相差小于等于1,考虑特殊情况根节点的左子树或右子树为空。

    ac代码:

     1 public class Solution {
     2     public boolean IsBalanced_Solution(TreeNode root) {
     3         if(root==null)
     4             return true;
     5         dfs(root,0);
     6         if(max==min&&max>1&&root.right==null)
     7             return false;
     8         if(max==min&&max>1&&root.left==null)
     9             return false;
    10         if(min==max||min+1==max)
    11             return true;
    12         else
    13             return false;
    14     }
    15     int max=0;
    16     int min=99999999;
    17      void  dfs(TreeNode root,int t){
    18         t++;
    19         if(root.left==null&&root.right==null){
    20             max=Math.max(max, t);
    21             min=Math.min(min, t);
    22         }
    23         if(root.left!=null){
    24             dfs(root.left,t);
    25         }
    26         if(root.right!=null){
    27             dfs(root.right,t);
    28         }
    29     }
    30 }
  • 相关阅读:
    初识计算机
    前端html css
    mysql高级
    mysql多表查询
    mysql数据库查询
    mysql表关系
    mysql数据类型
    mysql数据库介绍
    异步回调 协程
    GIL-全局解释器锁
  • 原文地址:https://www.cnblogs.com/llsq/p/8809674.html
Copyright © 2011-2022 走看看