2014-03-19 03:30

题目:判断一个二叉树是否为平衡二叉树,即左右子树高度相差不超过1。

解法:递归算高度并判断即可。

代码:

 1 // 4.1 Implement an algorithm to check if a bianry tree is height-balanced.
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <unordered_map>
 5 using namespace std;
 6 
 7 struct TreeNode {
 8     int val;
 9     TreeNode *left;
10     TreeNode *right;
11     
12     TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {};
13 };
14 
15 void constructBinaryTree(TreeNode *&root)
16 {
17     int val;
18     
19     scanf("%d", &val);
20     if (val <= 0) {
21         root = nullptr;
22     } else {
23         root = new TreeNode(val);
24 
25         constructBinaryTree(root->left);
26         constructBinaryTree(root->right);
27     }
28 }
29 
30 void clearBinaryTree(TreeNode *&root) {
31     if (root == nullptr) {
32         return;
33     } else {
34         clearBinaryTree(root->left);
35         clearBinaryTree(root->right);
36         delete root;
37         root = nullptr;
38     }
39 }
40 
41 void calcHeights(TreeNode *root, unordered_map<TreeNode *, int> &heights)
42 {
43     if (root == nullptr) {
44         heights[root] = 0;
45     } else {
46         calcHeights(root->left, heights);
47         calcHeights(root->right, heights);
48         heights[root] = max(heights[root->left], heights[root->right]) + 1;
49     }
50 }
51 
52 bool isBalanced(TreeNode *root, unordered_map<TreeNode *, int> &heights)
53 {
54     if (root == nullptr) {
55         return true;
56     } else {
57         return abs(heights[root->left] - heights[root->right]) <= 1;
58     }
59 }
60 
61 int main()
62 {
63     TreeNode *root;
64     unordered_map<TreeNode *, int> heights;
65     
66     while (true) {
67         constructBinaryTree(root);
68         if (root == nullptr) {
69             break;
70         }
71         
72         calcHeights(root, heights);
73         if (isBalanced(root, heights)) {
74             printf("Yes\n");
75         } else {
76             printf("No\n");
77         }
78         heights.clear();
79         clearBinaryTree(root);
80     }
81     
82     return 0;
83 }

 

 posted on 2014-03-19 03:32  zhuli19901106  阅读(310)  评论(0编辑  收藏  举报