与其明天开始,不如现在行动!
文章目录
- 是否平衡二叉树
- 💎总结
是否平衡二叉树
题目
给定一颗二叉树的头节点head,返回这颗二叉树是不是平衡二叉树
平衡二叉树就是这个树的所有子树和它自己,左右子树高度差不超过1
- 递归
- 先判断左子树是否平衡
- 再判断右子树是否平衡
- 再整体判断
代码
public class IsBalancedTree {public static class Node {public int val;public Node left;public Node right;public Node(int val) {this.val = val;}}public static class Info {public int height;public boolean balancedFlag;public Info(int height, boolean balancedFlag) {this.height = height;this.balancedFlag = balancedFlag;}}public static boolean isBalanced(Node head) {return balancedProcess(head).balancedFlag;}private static Info balancedProcess(Node head) {if (head == null) {return new Info(0, true);}Info leftInfo = balancedProcess(head.left);Info rightInfo = balancedProcess(head.right);int height = Math.max(leftInfo.height, rightInfo.height) + 1;boolean flag = leftInfo.balancedFlag && rightInfo.balancedFlag && Math.abs(leftInfo.height - rightInfo.height) <= 1;return new Info(height, flag);}// 测试public static void main(String[] args) {Node head = new Node(1);head.left = new Node(2);head.right = new Node(3);head.left.left = new Node(4);head.left.right = new Node(5);head.right.left = new Node(6);head.right.right = new Node(7);head.right.right.right = new Node(8);head.right.right.right.right = new Node(9);System.out.println(isBalanced(head));}
}
💎总结
本文中若是有出现的错误请在评论区或者私信指出,我再进行改正优化,如果文章对你有所帮助,请给博主一个宝贵的三连,感谢大家😘!!!