15算法课程 110. Balanced Binary Tree

来源:互联网 发布:淘宝买家怎么快速升钻 编辑:程序博客网 时间:2024/05/26 02:53

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.


solution:使用一个计算深度的函数来做辅助


code:

class Solution {public:int cntHeight(TreeNode *root) {    if(root == NULL) return 0;    int l = cntHeight(root->left);    int r = cntHeight(root->right);    if(l < 0 || r < 0 || abs(l-r) > 1) return -1; //自定义 return -1,表示不平衡的情况    else  return max(l, r) + 1;}bool isBalanced(TreeNode *root) {    if(root == NULL) return true;        int l = cntHeight(root->left);    int r = cntHeight(root->right);    if(l < 0 || r < 0 || abs(l-r) > 1) return false;    else return true;}};


原创粉丝点击