平衡二叉树-剑指Offer

平衡二叉树

题目描述

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

思路

  1. 在计算二叉树的深度的基础上加以判断是否是平衡二叉树
  2. 用后序遍历,在遍历一个节点之前我们已经遍历了他的左右子树,在遍历每个节点的时候记录他的深度,当该子树是平衡二叉树的时候我们返回它的深度,若不是则返回-1

代码

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        boolean result = false;
        if (root == null) {
            return true;
        }
        if (isBalanceTree(root) > 0) {
            result = true;
        }
        return result;
    }
    public int isBalanceTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = isBalanceTree(root.left);
        int right = isBalanceTree(root.right);
        if (left >= 0 && right >= 0) {
            int diff = left - right;
            if (diff >= -1 && diff <= 1) {
                int result = 1 + ((left > right) ? left: right);
                return result;
            }
        }
        return -1;
    }
}
原文地址:https://www.cnblogs.com/rosending/p/5657262.html