Given a binary tree, determine if it is height-balanced.java
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.node
題目 | Balanced Binary Tree |
經過率 | 32.1% |
難度 | Easy |
題目是判斷是不是平衡二叉樹this
平衡二叉樹定義(AVL):它或者是一顆空樹,或者具備如下性質的二叉樹:它的左子樹和右子樹的深度之差的絕對值不超過1,且它的左子樹和右子樹都是一顆平衡二叉樹。spa
關鍵點:深度優先遍歷、遞歸;code
咱們的判斷過程從定義入手便可:blog
1. 若爲空樹,則爲true;遞歸
2. 若不爲空樹,調用getHeight()方法,若爲二叉樹此方法返回的是樹的高度,不然返回-1;get
3. 在getHeight()方法中,利用遞歸的思想處理左右子樹;it
java代碼:io
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { if(root==null) return true; if(getHeight(root) == -1) return false; return true; } public int getHeight(TreeNode root){ if(root == null) return 0; int left = getHeight(root.left); int right = getHeight(root.right); if(left==-1 || right==-1) return -1; if(Math.abs(left-right)>1) return -1; return Math.max(left,right)+1; } }