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

来源:互联网 发布:python视频教程在线 编辑:程序博客网 时间:2024/05/22 03:47

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

平衡二叉树,又称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         else22             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     }

 

 

 

阅读全文
0 0