Leetcode 110.平衡二叉树
题目要求
示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:true
示例 2:
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false

示例 3:
输入:root = []
输出:true
后序遍历判断平衡二叉树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
class Solution { public boolean isBalanced(TreeNode root) { if(root == null) return true; int reesult = height(root); if(reesult == -1) return false; else return true; }
public int height(TreeNode root){ if (root == null) return 0;
int leftdepth = height(root.left); if (leftdepth == -1) return -1; int rightdepth = height(root.right); if (rightdepth == -1) return -1;
if (Math.abs(leftdepth - rightdepth) > 1) { return -1; }else { return Math.max(leftdepth, rightdepth) + 1; } } }
|