【Leetcode】110. Balanced Binary Tree
Question:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3 / \ 9 20 / \ 15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 / \ 2 2 / \ 3 3 / \ 4 4
Return false.
定义:
平衡二叉树(AVL):1、空二叉树是AVL树;
2、如果T是一颗非空的二叉搜索树,TL和TR分别是其左子树和右子树,那么当T满足一下条件时,T是一颗AVL树:
(1)TL和TR是AVL树;
(2)|HL-HR|<=1,HL和HR分别是左子树和右子树的高度
算法思路:采用递归的思想,从root节点进行递归的调用。分别计算各个节点的左右子树的高度;若高度差大于1或者计算的高度不合法(即高度小于零))则返回-1(表示不是平衡树),否则返回子树的最大高度加一。
package easy; import dataStructure.TreeNode; public class L110BalancedBinaryTree { public boolean isBalanced(TreeNode root) { if(root==null) return true; int depth=calHeight(root); return depth>=0; } private int calHeight(TreeNode root) { // TODO Auto-generated method stub if(root==null){ return 0; } int left=0;int right=0; if(root.left!=null){ left=calHeight(root.left); } if(left==-1)return -1; if(root.right!=null){ right=calHeight(root.right); } if(right==-1) return -1; if(Math.abs(left-right)>1 ||left<0 ||right<0){ return -1; }else{ return Math.max(left,right)+1; } } public static void main(String[] args) { TreeNode root = new TreeNode(5); TreeNode node1 = new TreeNode(4); TreeNode node2 = new TreeNode(8); TreeNode node3 = new TreeNode(11); TreeNode node4 = new TreeNode(13); TreeNode node5 = new TreeNode(4); TreeNode node6 = new TreeNode(7); TreeNode node7 = new TreeNode(2); TreeNode node8 = new TreeNode(1); root.left = node1; root.right = node2; node1.left = node3; node2.left = node4; node2.right = node5; node3.left = node6; node3.right = node7; node5.right = node8; node1.right = null; node6.left = null; node6.right = null; node7.left = null; node7.right = null; node4.left = null; node4.right = null; node5.left = null; node8.left = null; node8.right = null; L110BalancedBinaryTree l110 = new L110BalancedBinaryTree(); boolean isBanlace = l110.isBalanced(root); System.out.println(isBanlace); System.out.println("~~~~~~~~~~~~~~"); TreeNode n1=new TreeNode(1); TreeNode n2=new TreeNode(2); TreeNode n3= new TreeNode(3); n1.left=null; n1.right=n2; n2.left=null; n2.right=n3; n3.left=null; n3.right=null; System.out.println(l110.isBalanced(n1)); } }