[Link to this article]
Http://www.cnblogs.com/hellogiser/p/is-balanced-tree.html
【Question]
Enter the root node of a binary tree to determine whether the tree is balanced. If the depth difference between left and right Subtrees of any node in a binary tree does not exceed 1, it is a balanced binary tree. For example, the binary tree in is a balanced binary tree:
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
50
51
52 # Include "stdafx. h"
# Include <cmath>
# Include <algorithm>
/*
Version: 1.0
Author: hellogiser
Blog: http://www.cnblogs.com/hellogiser
Date:
*/
// Binary tree node struct
Struct BinaryTreeNode
{
Int value;
BinaryTreeNode * left;
BinaryTreeNode * right;
};
// Get depth of a binary tree
Int TreeDepth (BinaryTreeNode * root)
{
// The depth of a empty tree is 0
If (NULL = root)
Return 0;
// The depth of left sub-tree
Int nLeft = TreeDepth (root-> left );
// The depth of right sub-tree
Int nRight = TreeDepth (root-> right );
// Depth is the binary tree
Return (nLeft> nRight )? (NLeft + 1): (nRight + 1 );
// Return max (nLeft, nRight) + 1;
}
// Is balanced tree in O (n ^ 2)
Bool IsBalanced (BinaryTreeNode * root)
{
If (NULL = root)
Return true;
If (! IsBalanced (root-> left ))
Return false;
If (! IsBalanced (root-> right ))
Return false;
Int leftDepth = TreeDepth (root-> left );
Int rightDepth = TreeDepth (root-> right );
If (abs (leftDepth-rightDepth)> 1)
Return false;
Else
Return true;
}
PartyCase2]
The depth is calculated in the process of determining whether the left and right subtree is balanced, so that the depth of the left and right subtree does not need to be calculated repeatedly when the parent node is balanced. ItsThe time complexity is O (n).
[Code]
C ++ Code
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 |
|
// Is balanced tree in O (n) Bool IsBalanced (BinaryTreeNode * root, int & depth) { If (NULL = root) { Depth = 0; Return true; }
Int leftDepth, rightDepth; If (! IsBalanced (root-> left, leftDepth )) Return false; If (! IsBalanced (root-> right, rightDepth )) Return false;
// Get root depth without visiting left and right sub-trees Depth = (leftDepth> rightDepth )? (LeftDepth + 1): (rightDepth + 1 ); If (abs (leftDepth-rightDepth)> 1) Return false; Else Return true; }
// Is balanced tree Bool IsBalancedTree (BinaryTreeNode * root) { Int depth; Return IsBalanced (root, depth ); } |
[Reference]
Http://zhedahht.blog.163.com/blog/static/25411174201142733927831/
Http://blog.csdn.net/zjull/article/details/11646591
Http://blog.csdn.net/luckyxiaoqiang/article/details/7518888
[Link to this article]
Http://www.cnblogs.com/hellogiser/p/is-balanced-tree.html