码迷,mamicode.com
首页 > 其他好文 > 详细

Balanced Binary Tree(平衡二叉树)

时间:2017-09-16 23:17:13      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:高度   turn   leetcode   pre   utf-8   tree node   his   int   sub   

来源: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(平衡二叉树)

标签:高度   turn   leetcode   pre   utf-8   tree node   his   int   sub   

原文地址:http://www.cnblogs.com/renzongxian/p/7533097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!