首页 > 其他 > 详细

39平衡二叉树

时间:2018-01-02 14:59:54      阅读:209      评论:0      收藏:0      [点我收藏+]

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路:
利用上一题树的深度。
再遍历树的每个节点时,调用depth得到左右子树的深度,如果每个节点的左右子树的深度差都不超过
1,则此树是一个平衡二叉树。

 1 public class Solution {
 2     public boolean IsBalanced_Solution(TreeNode root) {
 3         if(root==null) return true;
 4         int left = depth(root.left);
 5         int right = depth(root.right);
 6         if(Math.abs(left-right)>1) return false;
 7         return IsBalanced_Solution(root.left) &&IsBalanced_Solution(root.right);
 8     }
 9     private int depth(TreeNode root){
10         if(root==null) return 0;
11         int left = depth(root.left);
12         int right = depth(root.right);
13         return left>right?left+1:right+1;
14     }
15 }

 

39平衡二叉树

原文:https://www.cnblogs.com/zle1992/p/8176749.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!