LeetCode 110 Balanced Binary Tree 平衡二叉树
LeetCode 110 Balanced Binary Tree
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3/ \9 20/ \15 7Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1/ \2 2/ \3 3/ \4 4Return false.
Solution 1:
這是和求最大深度的結合在一起,可以考慮寫個helper函數找到拿到左右子樹的深度,然后遞歸調用isBalanced函數判斷左右子樹是否也是平衡的,得到最終的結果。時間復雜度O(n^2)
Solution 2:
解題思路:
再來看個O(n)的遞歸解法,相比上面的方法要更巧妙。二叉樹的深度如果左右相差大于1,則我們在遞歸的helper函數中直接return -1,那么我們在遞歸的過程中得到左子樹的深度,如果=-1,就說明二叉樹不平衡,也得到右子樹的深度,如果=-1,也說明不平衡,如果左右子樹之差大于1,返回-1,如果都是valid,則每層都以最深的子樹深度+1返回深度。
總結
以上是生活随笔為你收集整理的LeetCode 110 Balanced Binary Tree 平衡二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 10.19文件管理课程笔记
- 下一篇: Java用户自定义函数