日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 110 Balanced Binary Tree 平衡二叉树

發布時間:2025/3/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 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.

Solution 1:
這是和求最大深度的結合在一起,可以考慮寫個helper函數找到拿到左右子樹的深度,然后遞歸調用isBalanced函數判斷左右子樹是否也是平衡的,得到最終的結果。時間復雜度O(n^2)

public boolean isBalanced(TreeNode root) {if (root == null) {return true;}int leftDep = depthHelper(root.left);int rightDep = depthHelper(root.right);if (Math.abs(leftDep - rightDep) <= 1 && isBalanced(root.left) && isBalanced(root.right)) {return true;}return false;}private int depthHelper(TreeNode root) {if (root == null) {return 0;}return Math.max(depthHelper(root.left), depthHelper(root.right)) + 1;}

Solution 2:
解題思路:
再來看個O(n)的遞歸解法,相比上面的方法要更巧妙。二叉樹的深度如果左右相差大于1,則我們在遞歸的helper函數中直接return -1,那么我們在遞歸的過程中得到左子樹的深度,如果=-1,就說明二叉樹不平衡,也得到右子樹的深度,如果=-1,也說明不平衡,如果左右子樹之差大于1,返回-1,如果都是valid,則每層都以最深的子樹深度+1返回深度。

public boolean isBalanced(TreeNode root) {return dfsHeight(root) != -1;}//helper function, get the heightpublic int dfsHeight(TreeNode root){if (root == null) {return 0;}int leftHeight = dfsHeight(root.left);if (leftHeight == -1) {return -1;}int rightHeight = dfsHeight(root.right);if (rightHeight == -1) {return -1;}if (Math.abs(leftHeight - rightHeight) > 1) {return -1;}return Math.max(leftHeight, rightHeight) + 1;}

總結

以上是生活随笔為你收集整理的LeetCode 110 Balanced Binary Tree 平衡二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。