题目:
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.
解题思路:
递归求解,注意在求解过程中需要记录左子树和右子树的高度。
代码:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool judge(TreeNode *node, int &depth) { 13 if (node == NULL) { 14 depth = 0; 15 return true; 16 } 17 18 int left_dep, right_dep; 19 bool left_is_balanced = judge(node->left, left_dep); 20 bool right_is_balanced = judge(node->right, right_dep); 21 22 depth = max(left_dep, right_dep) + 1; 23 24 return left_is_balanced && right_is_balanced && (abs(left_dep - right_dep) < 2); 25 } 26 bool isBalanced(TreeNode *root) { 27 int depth = 0; 28 return judge(root, depth); 29 } 30 };