leetcode110 判断是否是平衡二叉树 Java

it2022-05-05  249

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isBalanced(TreeNode root) { if(root==null) return false; int i=getH(root.left); int j=getH(root.right); if(i<0||j<0||Math.abs(i-j)>1) return false; return true; } public int getH(TreeNode root){ if(root==null) return 0; int a=getH(root.left); int b=getH(root.right); if(Math.abs(a-b)>1||a<0||b<0){ return -1; } return a>b?a+1:b+1; } }

 


最新回复(0)