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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Leet Code OJ 110. Balanced Binary Tree [Difficulty: Easy]

發布時間:2024/2/28 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leet Code OJ 110. Balanced Binary Tree [Difficulty: Easy] 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目:
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。

分析:
這其實就是判斷是否是平衡二叉樹。
平衡二叉樹,又稱AVL樹。它或者是一棵空樹,或者是具有下列性質的二叉樹:它的左子樹和右子樹都是平衡二叉樹,且左子樹和右子樹的高度之差之差的絕對值不超過1。
下面的做法,遞歸遍歷每個節點,每次遞歸,都獲取左右子樹的高度進行判斷,采用-1作為已經檢測到不平衡的標志位,其余情況返回當前子樹的高度,用作上一層遞歸判斷。

代碼:

/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ public class Solution {public boolean isBalanced(TreeNode root) {int depth=getDepth(root,0);return depth!=-1;//-1代表子樹出現不平衡}public int getDepth(TreeNode root,int length){if(root==null){return length;}int leftDepth=getDepth(root.left,length+1);int rightDepth=getDepth(root.right,length+1);if(leftDepth==-1||rightDepth==-1||leftDepth-rightDepth>1||rightDepth-leftDepth>1){return -1;}return leftDepth>rightDepth?leftDepth:rightDepth;} }

總結

以上是生活随笔為你收集整理的Leet Code OJ 110. Balanced Binary Tree [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。

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