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

 

posted @ 2017-09-16 21:48  HitAnyKey  阅读(251)  评论(0编辑  收藏  举报