《Cracking the Coding Interview》——第4章:树和图——题目1
2014-03-19 03:32
381 查看
2014-03-19 03:30
题目:判断一个二叉树是否为平衡二叉树,即左右子树高度相差不超过1。
解法:递归算高度并判断即可。
代码:
题目:判断一个二叉树是否为平衡二叉树,即左右子树高度相差不超过1。
解法:递归算高度并判断即可。
代码:
// 4.1 Implement an algorithm to check if a bianry tree is height-balanced. #include <algorithm> #include <cstdio> #include <unordered_map> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {}; }; void constructBinaryTree(TreeNode *&root) { int val; scanf("%d", &val); if (val <= 0) { root = nullptr; } else { root = new TreeNode(val); constructBinaryTree(root->left); constructBinaryTree(root->right); } } void clearBinaryTree(TreeNode *&root) { if (root == nullptr) { return; } else { clearBinaryTree(root->left); clearBinaryTree(root->right); delete root; root = nullptr; } } void calcHeights(TreeNode *root, unordered_map<TreeNode *, int> &heights) { if (root == nullptr) { heights[root] = 0; } else { calcHeights(root->left, heights); calcHeights(root->right, heights); heights[root] = max(heights[root->left], heights[root->right]) + 1; } } bool isBalanced(TreeNode *root, unordered_map<TreeNode *, int> &heights) { if (root == nullptr) { return true; } else { return abs(heights[root->left] - heights[root->right]) <= 1; } } int main() { TreeNode *root; unordered_map<TreeNode *, int> heights; while (true) { constructBinaryTree(root); if (root == nullptr) { break; } calcHeights(root, heights); if (isBalanced(root, heights)) { printf("Yes\n"); } else { printf("No\n"); } heights.clear(); clearBinaryTree(root); } return 0; }
相关文章推荐
- 《Cracking the Coding Interview》——第4章:树和图——题目3
- 《Cracking the Coding Interview》——第4章:树和图——题目4
- 《Cracking the Coding Interview》——第4章:树和图——题目5
- 《Cracking the Coding Interview》——第4章:树和图——题目6
- 《Cracking the Coding Interview》——第4章:树和图——题目7
- 《Cracking the Coding Interview》——第4章:树和图——题目8
- 《Cracking the Coding Interview》——第4章:树和图——题目9
- 《Cracking the Coding Interview》——第4章:树和图——题目2
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目3
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目5
- 《Cracking the Coding Interview》——第13章:C和C++——题目8
- 《Cracking the Coding Interview》——第14章:Java——题目3
- 《Cracking the Coding Interview》——第18章:难题——题目5
- 《Cracking the Coding Interview》——第3章:栈和队列——题目5
- 《Cracking the Coding Interview》——第6章:智力题——题目1
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目1
- 《Cracking the Coding Interview》——第9章:递归和动态规划——题目10
- 《Cracking the Coding Interview》——第11章:排序和搜索——题目7
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目4
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目6