标签:style blog color io ar for sp div on
/** * 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; } }
于是我想到了 bottom-up 也就是后序遍历
/** * 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; } }
苦于让height() return height 如果不必配就return false. 下面有一个非常聪明的方法。
/** * 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; } }
标签:style blog color io ar for sp div on
原文地址:http://www.cnblogs.com/leetcode/p/4020092.html