/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean isBalanced(TreeNode root) { if(root==null) return true; int l = height(root.left); int r = height(root.right); if(Math.abs(l-r)>1) return false; return isBalanced(root.left) && isBalanced(root.right); } public int height(TreeNode root){ if(root == null) return 0; if(root.left == null && root.right == null) return 1; int l = height(root.left); int r = height(root.right); return Math.max(l,r) + 1; }}
So I thought of bottom-up, that is, post-sequential traversal.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { boolean check = true; public boolean isBalanced(TreeNode root) { if(root==null) return true; int l = height(root.left); int r = height(root.right); if(Math.abs(l-r)>1) return false; return check; } public int height(TreeNode root){ if(root == null) return 0; if(root.left == null && root.right == null) return 1; int l = height(root.left); int r = height(root.right); if(Math.abs(l-r)>1) check = false; return Math.max(l,r) + 1; }}
However, if height () return height does not need to be configured, return false. There is a very clever method below.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { boolean check = true; public boolean isBalanced(TreeNode root) { if(root==null) return true; if(getHeight(root)== -1) return false; return true; } public int getHeight(TreeNode root){ if(root == null) return 0; int l = getHeight(root.left); int r = getHeight(root.right); if(l == -1 || r == -1) return -1; if(Math.abs(l-r)>1) return -1; return Math.max(l,r) + 1; }}
Balanced Binary Tree