MENU

LeetCode110. 平衡二叉树

August 9, 2018 • Read: 3401 • LeetCode阅读设置

题目链接:LeetCode110展开目录

题解展开目录

平衡二叉树的定义是一个二叉树每个结点的左右两个子树的高度差绝对值不超过 1(可以是 1),用一个结构体来保存某个结点的信息(包括是否是平衡树,高度多少),算法流程如下:

  1. 判断当前结点的左子树是否为平衡二叉树
  2. 判断当前结点的右子树是否为平衡二叉树
  3. 判断左子树与右子树的高度差的绝对值是否大于 1

假设左子树已经不是平衡二叉树了,2,3 都不用判断了,3 判断的前提是 1,2 都满足条件

代码展开目录
  • /**
  • * Definition for a binary tree node.
  • * public class TreeNode {
  • * int val;
  • * TreeNode left;
  • * TreeNode right;
  • * TreeNode(int x) { val = x; }
  • * }
  • */
  • class Solution {
  • public ReturnData process(TreeNode head) {
  • if(head == null)
  • return new ReturnData(true,0);
  • ReturnData leftData = process(head.left);
  • if(!leftData.isB)
  • return new ReturnData(false,0);
  • ReturnData rightData = process(head.right);
  • if(!rightData.isB)
  • return new ReturnData(false,0);
  • if(Math.abs(leftData.h - rightData.h) > 1)
  • return new ReturnData(false,0);
  • return new ReturnData(true,Math.max(leftData.h,rightData.h) + 1);//因为还要算上当前结点,所以要+1
  • }
  • public boolean isBalanced(TreeNode root) {
  • return process(root).isB;
  • }
  • }
  • class ReturnData {
  • boolean isB;
  • int h;
  • ReturnData(boolean isB,int h) {
  • this.isB = isB;
  • this.h = h;
  • }
  • }
Last Modified: May 12, 2021
Archives Tip
QR Code for this page
Tipping QR Code