1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49


struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


/**
* Calculate the height of the tree begin with TreeNode
* @param n Root node to measure the height
* @param balanced Indicate if the tree is balanced, if not no need to calculate anymore
* @return The height of tree or -1 if tree is not balanced
*/
int heightOf(TreeNode *n, bool& balanced) { if (n == NULL) { return 0; } // process left/right child, // stop process when tree is not balanced int lh = heightOf(n->left, balanced); if (!balanced) return -1; int rh = heightOf(n->right, balanced); if (!balanced) return -1; // test if current node is balanced, // if not, set balanced to false, and stop process if (lh-rh > 1 || rh-lh > 1) { balanced = false; return -1; } //return max height of left/right height plus 1 as height of current node return (lh>rh? lh: rh)+1; } bool isBalanced(TreeNode *root) { bool balanced = true; heightOf(root, balanced); return balanced; }
View Program Text


Test Status