问题:给一个二叉树,写一个算法判断这个树是否是balanced。算法
Solution #1.ide
第一次遇到这个问题时个人解法,以下:函数
public class Solution { public boolean isBalanced(TreeNode root) { if(root == null){ return true; } int depthOfLeft = getDepth(root.left, 1); int depthOfRight = getDepth(root.right, 1); if(Math.abs(depthOfRight-depthOfLeft) > 1){ return false; }else{ return isBalanced(root.left) && isBalanced(root.right); } } private int getDepth(TreeNode tree, int currentDepth){ if(tree == null){ return currentDepth; } return Math.max(getDepth(tree.left, currentDepth+1), getDepth(tree.right, currentDepth+1)); } }
写了一个getDepth()函数,访问每一个节点都要调用一次这个函数。这个Solution也经过了leetcode的验证程序,可是后来想了想,I can do better.优化
下面是我对此算法时间复杂度的分析,当整棵树有N个节点时,时间复杂度是O(N*logN).idea
Solution #2:spa
今天我想出了更好的Solution,只需一遍DFS,能够将时间复杂度优化到O(N),可是空间复杂度一样是O(N).code
public class CheckTreeBalanced { HashMap<TreeNode, Integer> heights = new HashMap<TreeNode, Integer>(); // The idea is to run DFS once boolean isBalanced(TreeNode root){ if(root == null){ heights.put(null, 0); return true; } if( isBalanced(root.left) && isBalanced(root.right) ){ if(Math.abs(heights.get(root.left) - heights.get(root.right)) > 1){ return false; }else{ int currentHeight = Math.max(heights.get(root.left), heights.get(root.right)) + 1; heights.put(root, currentHeight); return true; } }else{ return false; } } }
Solution #3:blog
Cracking the coding interview上看到另外一种解法,time complexity O(N), space complexity O(logN). 之因此占用logN的空间是由于这是DFS的特色,整棵树的高度H=logN,DFS必然会占用O(H), explicitly or implicitly.ci
该算法的思路是基于Solution #1的一种改进,把每一个节点的height信息和isBalanced信息融合到一块儿个变量中:leetcode
若是该变量>=0,那么该节点是balanced而且该变量就是节点的height;
若是该变量<0,那么该节点是unbalanced,但同时咱们失去了它的height信息。
public class CheckTreeBalanced2 { public int checkHeight(TreeNode root){ if(root == null){ return 0; } int leftHeight = checkHeight(root.left); if(leftHeight == -1){ return -1; } int rightHeight = checkHeight(root.right); if(rightHeight == -1){ return -1; } int heightDiff = leftHeight - rightHeight; if(Math.abs(heightDiff) > 1){ return -1; }else{ return Math.max(leftHeight, rightHeight); } } public boolean isBalance(TreeNode root){ if(checkHeight(root) == -1){ return false; }else{ return true; } } }