Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.
Feel the tree needs a lot of tools, in fact, the method of transformation out, if you do this problem is convenient, to find the height of the tree, you can see the blog before. http://blog.csdn.net/my_jobs/article/details/47662437 so, directly according to test instructions transformation can be, on the code:
public Boolean isbalanced (TreeNode root) { if (root = null) return true; if (Math.Abs (maxDepth (root.left)-maxdepth (root.right)) > 1) return false; Return isbalanced (Root.left) && isbalanced (root.right); } private int maxDepth (TreeNode root) { if (root = null) return 0; Return Math.max (MaxDepth (Root.left), maxDepth (root.right)) +1; }
It is also a very refined code, but the obvious time complexity is higher. So now you can change the code, in the depth when the judgment is not balance.
public Boolean isbalanced (TreeNode root) { if (root = null) return true; if (depth (root) = =-1) return false; return true; } private int Depth (TreeNode root) { if (root = null) return 0; int left = depth (root.left); int right = depth (root.right); if (left = =-1 | | right =-1) return-1; if (Math.Abs (left-right) > 1) return-1; Return Math.max (left, right) +1; }
The first method is a bit of literal translation, which is a top-to-bottom order, but the second is a sequence from the bottom up. Because the calculation height is also from the bottom up process, so you can optimize the algorithm by the way!
In fact, this recursive nature of the tree, if it can be from the bottom up is a good optimization of the previous algorithm!!! How to comprehend such problems.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
leetcode-balanced Binary Tree