题目:
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.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3 / \ 9 20 / \ 15 7
Return true.
Example 2:Given the following tree [1,2,2,3,3,null,null,4,4]
:
1 / \ 2 2 / \ 3 3 / \ 4 4
Return false.
分析:
给定一个二叉树,判断它是否是高度平衡的二叉树。
一棵高度平衡二叉树定义为:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。
递归求解每个节点的左右两个子树的高度差的绝对值是否超过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 == nullptr) return true; return abs(height(root->left, 0)-height(root->right, 0)) <= 1 && isBalanced(root->left) && isBalanced(root->right); } int height(TreeNode* root, int h) { if(root == nullptr) return h; return max(height(root->left, h+1), height(root->right, h+1)); }};