Advertisement
sweet1cris

Untitled

Jan 9th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.87 KB | None | 0 0
  1. // Version 1: with ResultType
  2. /**
  3.  * Definition of TreeNode:
  4.  * public class TreeNode {
  5.  *     public int val;
  6.  *     public TreeNode left, right;
  7.  *     public TreeNode(int val) {
  8.  *         this.val = val;
  9.  *         this.left = this.right = null;
  10.  *     }
  11.  * }
  12.  */
  13. class ResultType {
  14.     public boolean isBalanced;
  15.     public int maxDepth;
  16.     public ResultType(boolean isBalanced, int maxDepth) {
  17.         this.isBalanced = isBalanced;
  18.         this.maxDepth = maxDepth;
  19.     }
  20. }
  21.  
  22. public class Solution {
  23.     /**
  24.      * @param root: The root of binary tree.
  25.      * @return: True if this Binary tree is Balanced, or false.
  26.      */
  27.     public boolean isBalanced(TreeNode root) {
  28.         return helper(root).isBalanced;
  29.     }
  30.    
  31.     private ResultType helper(TreeNode root) {
  32.         if (root == null) {
  33.             return new ResultType(true, 0);
  34.         }
  35.        
  36.         ResultType left = helper(root.left);
  37.         ResultType right = helper(root.right);
  38.        
  39.         // subtree not balance
  40.         if (!left.isBalanced || !right.isBalanced) {
  41.             return new ResultType(false, -1);
  42.         }
  43.        
  44.         // root not balance
  45.         if (Math.abs(left.maxDepth - right.maxDepth) > 1) {
  46.             return new ResultType(false, -1);
  47.         }
  48.        
  49.         return new ResultType(true, Math.max(left.maxDepth, right.maxDepth) + 1);
  50.     }
  51. }
  52.  
  53. // Version 2: without ResultType
  54. public class Solution {
  55.     public boolean isBalanced(TreeNode root) {
  56.         return maxDepth(root) != -1;
  57.     }
  58.  
  59.     private int maxDepth(TreeNode root) {
  60.         if (root == null) {
  61.             return 0;
  62.         }
  63.  
  64.         int left = maxDepth(root.left);
  65.         int right = maxDepth(root.right);
  66.         if (left == -1 || right == -1 || Math.abs(left-right) > 1) {
  67.             return -1;
  68.         }
  69.         return Math.max(left, right) + 1;
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement