Leet Code OJ 110. Balanced Binary Tree [Difficulty: Easy]
生活随笔
收集整理的這篇文章主要介紹了
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]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 1. Two
- 下一篇: Leet Code OJ 88. Mer