您的位置:首页 > 编程语言 > C#

LeetCode Online Judge 题目C# 练习 - Balanced Binary Tree

2012-10-24 23:36 591 查看
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 everynode never differ by more than 1.

public static bool BalancedBinaryTree(BTNode root)
{
if (root == null)
return true;

if(Math.Abs(GetDepth(root.Left) - GetDepth(root.Right)) >= 2)
return false;
else
return BalancedBinaryTree(root.Left) && BalancedBinaryTree(root.Right);
}

public static int GetDepth(BTNode root)
{
if (root == null)
return 0;
if (root.Left == null && root.Right == null)
return 1;
else
return 1 + Math.Max(GetDepth(root.Left), GetDepth(root.Right));


代码分析:

  看来是永无止境了,LeetCode上加了些Tree的题目,在做些吧,反正自己递归很弱。

  上面是递归Top-down的做法,不知有没有bottom-up的做法,DP之类的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: