剑指offer——平衡二叉树

来源:互联网 发布:sql having用法例子 编辑:程序博客网 时间:2024/06/07 07:42

题目描述

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


正解:
思路:后序遍历取它们的高度,然后依次判定它们的左右子树高度,返回它们的高度。并且需要递归它们的子树。时间复杂度o(n2)

跟金典里面的那题完全一样。

public class Solution {    public boolean IsBalanced_Solution(TreeNode root) {        // write code here        if(root==null)return true;     int left = getDeep(root.left);     int right = getDeep(root.right);     if(Math.abs(left-right)>1)return false;        //这里必须递归返回     else{     return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);     }    }         public int getDeep(TreeNode root){ if(root!=null){int left = getDeep(root.left);     int right = getDeep(root.right);     return left>right?left+1:right+1; }else{ return 0; } }}


原创粉丝点击