110. Balanced Binary Tree
Posted 咖啡中不塌缩的方糖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了110. Balanced Binary Tree相关的知识,希望对你有一定的参考价值。
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
可以先求出每个subtree的深度,然后比较。但不高效,时间复杂度为O(nlgn).因为每一次计算左右subtree深度为2*O(lgn), 然后递归n次。
public bool IsBalanced(TreeNode root) { if(root == null) return true; int left = TreeHeight(root.left); int right = TreeHeight(root.right); if ((left>=right+2)||(left+2<=right)) return false; return IsBalanced(root.left)&& IsBalanced(root.right); } public int TreeHeight(TreeNode root) { if(root == null) return 0; if(root.left == null && root.right == null) return 1; return Math.Max(TreeHeight(root.left), TreeHeight(root.right))+1; }
优化的方法为DFS,先check更小的subtree是否为Balanced Tree, 如果不是则直接返回false。参考http://www.cnblogs.com/grandyang/p/4045660.html
public bool IsBalanced(TreeNode root) { return !(TreeHeight(root)==-1); } public int TreeHeight(TreeNode root) { if(root == null) return 0; int left = TreeHeight(root.left); if(left == -1) return -1; int right = TreeHeight(root.right); if(right == -1) return -1; if ((left>=right+2)||(left+2<=right)) return -1; return Math.Max(left, right)+1; }
以上是关于110. Balanced Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章