public boolean isBalanced(TreeNode root) { return recur(root) != -1; } public int recur(TreeNode root) { // Follow-up traversal if (root == null) { return 0; } int left = recur(root.left); if(left == -1) { return -1; } int right = recur(root.right); if(right == -1) { return -1; } // If the depth of the left and right subtrees is less than 2, return the depth, otherwise return -1 to determine that it is not balanced return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1; }
Sword refers to Offer-57 balanced binary tree
Guess you like
Origin blog.csdn.net/a792396951/article/details/114261038
Ranking