|
| 1 | +/* |
| 2 | +Given a binary tree, determine if it is height-balanced. |
| 3 | +
|
| 4 | +For this problem, a height-balanced binary tree is defined as: |
| 5 | +
|
| 6 | +a binary tree in which the left and right subtrees of every node differ in height by no more than 1. |
| 7 | +
|
| 8 | + |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +
|
| 12 | +Given the following tree [3,9,20,null,null,15,7]: |
| 13 | +
|
| 14 | + 3 |
| 15 | + / \ |
| 16 | + 9 20 |
| 17 | + / \ |
| 18 | + 15 7 |
| 19 | +Return true. |
| 20 | +
|
| 21 | +Example 2: |
| 22 | +
|
| 23 | +Given the following tree [1,2,2,3,3,null,null,4,4]: |
| 24 | +
|
| 25 | + 1 |
| 26 | + / \ |
| 27 | + 2 2 |
| 28 | + / \ |
| 29 | + 3 3 |
| 30 | + / \ |
| 31 | + 4 4 |
| 32 | +Return false. |
| 33 | +* |
| 34 | +
|
| 35 | +
|
| 36 | +Solution 1 O(n2), Solution O(n) |
| 37 | +
|
| 38 | +/ |
| 39 | +
|
| 40 | +/** |
| 41 | + * Definition for a binary tree node. |
| 42 | + * struct TreeNode { |
| 43 | + * int val; |
| 44 | + * TreeNode *left; |
| 45 | + * TreeNode *right; |
| 46 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 47 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 48 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 49 | + * }; |
| 50 | + */ |
| 51 | +class Solution { |
| 52 | +public: |
| 53 | + bool isBalanced(TreeNode* root) { |
| 54 | + if ( !root ) return true; |
| 55 | + if ( !isBalanced( root->left ) ) return false; |
| 56 | + if ( !isBalanced( root->right ) ) return false; |
| 57 | + int DepthLeft = Depth( root->left ); |
| 58 | + int DepthRight = Depth( root->right ); |
| 59 | + if ( abs( DepthLeft - DepthRight ) > 1 ) return false; |
| 60 | + return true; |
| 61 | + } |
| 62 | + int Depth( TreeNode *root ) |
| 63 | + { |
| 64 | + if ( !root ) return 0; |
| 65 | + return max( Depth( root->left ), Depth( root->right ) ) + 1; |
| 66 | + } |
| 67 | +}; |
| 68 | + |
| 69 | +class Solution { |
| 70 | +public: |
| 71 | + bool isBalanced(TreeNode* root) { |
| 72 | + int height = 0; |
| 73 | + return Balanced( root, height ); |
| 74 | + } |
| 75 | + bool Balanced( TreeNode *root, int &height ) |
| 76 | + { |
| 77 | + if ( !root ) return true; |
| 78 | + int left = 0; |
| 79 | + int right = 0; |
| 80 | + if ( !Balanced( root->left, left ) ) return false; |
| 81 | + if ( !Balanced( root->right, right ) ) return false; |
| 82 | + if ( abs( left - right ) > 1 ) return false; |
| 83 | + height = max( left, right ) + 1; |
| 84 | + return true; |
| 85 | + } |
| 86 | +}; |
0 commit comments