Balanced Binary Tree(平衡二叉树)

Posted 人总闲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Balanced Binary Tree(平衡二叉树)相关的知识,希望对你有一定的参考价值。

来源:https://leetcode.com/problems/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,并且左右两个子树都是一棵平衡二叉树。

Java

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     private boolean isBalancedFlag = true;
12     private int getDepth(TreeNode root) {
13         if(root == null) {
14             return 0;
15         }
16         int leftDepth = getDepth(root.left) + 1;
17         int rightDepth = getDepth(root.right) + 1;
18         if(Math.abs(leftDepth - rightDepth) > 1) {
19             isBalancedFlag = false;
20         }
21         return leftDepth > rightDepth ? leftDepth : rightDepth;
22     }
23     public boolean isBalanced(TreeNode root) {
24         getDepth(root);
25         return isBalancedFlag;
26     }
27 }// 1 ms

Python

 1 # -*- coding:utf-8 -*-
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 class Solution:
 8     __is_balanced = True
 9     def getDepth(self, pRoot):
10         if pRoot == None:
11             return 0
12         left_depth = self.getDepth(pRoot.left)
13         right_depth = self.getDepth(pRoot.right)
14         if abs(left_depth-right_depth) > 1:
15             self.__is_balanced = False
16         return left_depth+1 if left_depth>right_depth else right_depth+1
17     def IsBalanced_Solution(self, pRoot):
18         self.getDepth(pRoot)
19         return self.__is_balanced

 

以上是关于Balanced Binary Tree(平衡二叉树)的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Balanced binary tree平衡二叉树

LeetCode 110 Balanced Binary Tree(平衡二叉树)(*)

110. Balanced Binary Tree 110.平衡二叉树

110. Balanced Binary Tree 110.平衡二叉树

平衡二叉树(Balanced Binary Tree 或 Height-Balanced Tree)又称AVL树

110 Balanced Binary Tree 平衡二叉树