平衡二叉树

解题思路:
这里复用了求二叉树的最大深度的代码。递归,反复比较左右二叉树深度的差值。
代码:
/*public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{ val = x; }
}*/
public static bool IsBalanced(TreeNode root)
{
if (root == null)
return true;
if (Math.Abs(MaxDepth(root.left) - MaxDepth(root.right)) > 1)
{
return false;
}
else return IsBalanced(root.left) && IsBalanced(root.right);
}//110平衡二叉树。(复用了最大深度的方法)
public static int selectcount(TreeNode root, int count)
{
if (root == null)
{
return count;
}
else
{
count++;
int a = Math.Max(selectcount(root.left, count), selectcount(root.right, count));
return a;
}
}
public static int MaxDepth(TreeNode root)
{
int count = 0;
int result = selectcount(root, count);
return result;
}//104二叉树的最大深度。


被折叠的 条评论
为什么被折叠?



