標籤:balancedbinarytree java leetcode
題目:
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.
題解:
判斷一顆二叉樹是不是平衡二叉樹 ,平衡二叉樹是每個節點都滿足指左右子樹的高度差小於1
我們通過計算每一個節點的左右高度差 一旦發現有不滿足的節點就將返回值置為-1 這兩句代碼if(left==-1) return -1;
if(right==-1) return -1保證只要出現一個高度差為-1的最終返回結果必然為-1,也就是說最終可以根據返回值是不是-1判斷是不是平衡二叉樹
代碼:
public static boolean isBalanced(TreeNode root) {if(treeHight(root)==-1)return false;else return true; }public static int treeHight(TreeNode root){if(root==null)return 0;else {int left=treeHight(root.left);int right=treeHight(root.right);if(left==-1) return -1;if(right==-1) return -1;if(Math.abs(left-right)>1)return -1;else {return 1+Math.max(treeHight(root.left), treeHight(root.right));}}}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
LeetCode110 Blanced Binary Tree Java 題解