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.
代码分析:
看来是永无止境了,LeetCode上加了些Tree的题目,在做些吧,反正自己递归很弱。
上面是递归Top-down的做法,不知有没有bottom-up的做法,DP之类的。
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之类的。
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Binary Tree Level Order Traversal
- LeetCode Online Judge 题目C# 练习 - Binary Tree Inorder Traversal
- LeetCode Online Judge 题目C# 练习 - Binary Tree Level Order Traversal II
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees
- LeetCode Online Judge 题目C# 练习 - Unique Binary Search Trees II
- LeetCode Online Judge 题目C# 练习 - Minimum Path Sum
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List II
- LeetCode Online Judge 题目C# 练习 - Remove Nth Node From End of List
- LeetCode Online Judge 题目C# 练习 - Search for a Range
- LeetCode Online Judge 题目C# 练习 - Scramble String
- LeetCode Online Judge 题目C# 练习 - Unique Paths II
- LeetCode Online Judge 题目C# 练习 - First Missing Positive
- LeetCode Online Judge 题目C# 练习 - Merge Intervals
- LeetCode Online Judge 题目C# 练习 - Generate Parentheses
- LeetCode Online Judge 题目C# 练习 - Reverse Integer
- LeetCode题目笔记(四) -- Check if a binary tree is balanced
- LeetCode Online Judge 题目C# 练习 - Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array
- LeetCode Online Judge 题目C# 练习 - N-QueensII
- LeetCode Online Judge 题目C# 练习 - Reverse Linked List II