leetcode 110. 平衡二叉树
生活随笔
收集整理的這篇文章主要介紹了
leetcode 110. 平衡二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
難度:簡單
頻次:61
題目:
給定一個二叉樹,判斷它是否是高度平衡的二叉樹。
本題中,一棵高度平衡二叉樹定義為:
一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1 。
解題思路:算深度+遞歸
注意
- 這里算深度的遞歸函數,其實跟104 二叉樹的最大深度的拆分樹的遞歸版本一行,基本一字不差。
- 在主函數里就兩個東西
- 判斷是否為空,為空返回true
- 判斷是否符合三個條件
- 當前子樹是否符合高度差為1
- 左子樹是否符合
- 右子樹是否符合
代碼
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/ class Solution {public boolean isBalanced(TreeNode root) {if(root==null) return true;//判斷是否平衡,任意一顆左子樹跟右子樹之間的高度差不超過1//也就是判斷3個條件:當前子樹是否符合,左子樹是否符合,右子樹是否符合return Math.abs(depth(root.left)-depth(root.right))<2&&isBalanced(root.left)&&isBalanced(root.right);}public int depth(TreeNode root){if(root==null) return 0;int left=depth(root.left);int right=depth(root.right);return Math.max(left,right)+1;} }總結
以上是生活随笔為你收集整理的leetcode 110. 平衡二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 105. 从前序与中序
- 下一篇: leetcode 8. 字符串转换整数