《LeetCode力扣练习》代码随想录——二叉树(平衡二叉树—Java)
刷题思路来源于 代码随想录
110. 平衡二叉树
-
二叉树-后序遍历
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/ class Solution {public boolean isBalanced(TreeNode root) {if (recursion(root) == -1) {return false;}return true;}private int recursion(TreeNode root) {if (root == null) {return 0;}int left = recursion(root.left);if (left == -1) {return -1;}int right = recursion(root.right);if (right == -1) {return -1;}if ((left > right ? (left - right) : (right - left)) > 1) {return -1;}return 1 + (left > right ? left : right);} }