平衡二叉树计算高度的同时判断是否平衡

来源:互联网 发布:淘宝刷销量被骗怎么办 编辑:程序博客网 时间:2024/04/28 19:37

今天一个朋友微软电话面试,问到一个问题,就是如题所述的,他问我他写的有没有错,挺难说的,然后我就随手写了一个版本(自我感觉良好)~

bool balance(Node* root, int& height) {    if (root == NULL) {        height = 0;        return true;    }    int left_height = 0, right_height = 0;    bool left_b = balance(root->left, left_height);    bool right_b = balance(root->right, right_height);    height = max(left_height, right_height) + 1;    if (left_height - right_height > 1 || right_height - left_height > 1)        return false;    return left_b && right_b;}
0 0
原创粉丝点击