标签:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode* root) { if (root == NULL) return true; if (Depth(root) == -1) { return false; } else { return true; } } int Depth(TreeNode* root) { if (root == NULL) return 0; int left_depth = Depth(root->left); int right_depth = Depth(root->right); if (left_depth == -1 || right_depth == -1 || abs(left_depth - right_depth) > 1) { return -1; } else { return left_depth > right_depth ? left_depth + 1 : right_depth + 1; } } };
[LeetCode] Balanced Binary Tree
标签:
原文地址:http://www.cnblogs.com/vincently/p/4716381.html