判断二叉树是不是平衡二叉树

匿名 (未验证) 提交于 2019-12-03 00:14:01
//判断一个树是不是平衡二叉树 //任何节点的左子树和右子树高度差不超过1 public class BalanceTree {      public static void main(String[] args) {          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(5);         root.right.left = new Node(6);         root.right.right = new Node(7);         root.left.right.left = new Node(8);         root.left.right.left.left = new Node(9);         System.out.println(isB(root));      }      public static boolean isB(Node head) {         return process(head).isB;     }      public static returnData process(Node head) {         if (head == null) {             return new returnData(true, 0);         }         returnData leftData = process(head.left);         if (!leftData.isB) {             return new returnData(false, 0);         }         returnData rightData = process(head.right);         if (!rightData.isB) {             return new returnData(false, 0);         }         if (Math.abs(leftData.h - rightData.h) > 1) {             return new returnData(false, 0);         }         return new returnData(true, Math.max(leftData.h, rightData.h) + 1);     }      public static class returnData {          boolean isB;         int h;          public returnData(boolean isB, int h) {             this.isB = isB;             this.h = h;         }      }      public static class Node {         Node left;         Node right;         int value;          public Node(int value) {             this.value = value;         }      }  }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!