Created
December 29, 2012 04:41
-
-
Save pdu/4404601 to your computer and use it in GitHub Desktop.
Given a binary tree, determine if it is AVL balanced tree.
http://www.leetcode.com/onlinejudge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Definition for binary tree | |
| * struct TreeNode { | |
| * int val; | |
| * TreeNode *left; | |
| * TreeNode *right; | |
| * TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
| * }; | |
| */ | |
| class Solution { | |
| public: | |
| void balance_depth(TreeNode *root, bool &ret, int &depth) { | |
| if (root == NULL) { | |
| ret = true; | |
| depth = 0; | |
| return; | |
| } | |
| bool left_ret = true, right_ret = true; | |
| int left_depth = 0, right_depth = 0; | |
| balance_depth(root->left, left_ret, left_depth); | |
| balance_depth(root->right, right_ret, right_depth); | |
| ret = left_ret & right_ret & (abs(left_depth - right_depth) <= 1); | |
| depth = 1 + max(left_depth, right_depth); | |
| } | |
| bool isBalanced(TreeNode *root) { | |
| if (root == NULL) { | |
| return true; | |
| } | |
| bool ret = true; | |
| int depth = 0; | |
| balance_depth(root, ret, depth); | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment