• 【IT笔试面试题整理】判断一个二叉树是否是平衡的?


    【试题描述】定义一个函数,输入一个链表,判断链表是否存在环路

    平衡二叉树,又称AVL树。它或者是一棵空树,或者是具有下列性质的二叉树:它的左子树和右子树都是平衡二叉树,且左子树和右子树的高度之差之差的绝对值不超过1。

    问题:判断一个二叉排序树是否是平衡二叉树这里是二叉排序树的定义解决方案:根据平衡二叉树的定义,如果任意节点的左右子树的深度相差不超过1,那这棵树就是平衡二叉树。首先编写一个计算二叉树深度的函数,利用递归实现。

    【参考代码】

    方法一:

     1 //返回树的最大深度  
     2     public static int Depth(Node root)
     3     {
     4         if (root == null)
     5             return 0;
     6         else
     7         {
     8             int ld = Depth(root.left);
     9             int rd = Depth(root.right);
    10             return 1 + (ld > rd ? ld : rd);
    11         }
    12     }
    13     
    14     public static boolean isBalanced(Node root)
    15     {
    16         if(root == null)
    17             return true;
    18         int dis = Depth(root.left) - Depth(root.right);
    19         if(dis >1 || dis < -1)
    20             return false;
    21         else
    22             return isBalanced(root.left) && isBalanced(root.right);
    23     }

    方法二:

     1     public static boolean isBalanced(Node root){
     2         return (maxDepth(root) - minDepth(root) <=1);
     3     }
     4     private static int minDepth(Node root)
     5     {
     6         if(root == null)
     7             return 0;
     8         return 1 + Math.min(minDepth(root.left), minDepth(root.right));
     9     }
    10     private static int maxDepth(Node root)
    11     {
    12         if(root == null)
    13             return 0;
    14         return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    15     }
  • 相关阅读:
    Editplus中添加System.out.println()快捷键
    API使用
    项目有两个红点
    no console to display at this time
    startup.bat闪退问题
    filter的dispatcher节点
    【DP专题】——洛谷P2467地精部落
    输入年月日,计算这是该年中第几天
    输出N以内的完整数
    python中关于EOF的tips
  • 原文地址:https://www.cnblogs.com/WayneZeng/p/9290757.html
Copyright © 2020-2023  润新知