CareerCup 4.1

来源:互联网 发布:淘宝lisa国潮是正品吗 编辑:程序博客网 时间:2024/06/07 05:09

4.1 Implement a function to check if a binary tree is balanced. For the purpose of this question, a balanced tree is defined to be a tree such that the height of the two subtrees of any node never differ by more than one.

struct TreeNode {    int data;    TreeNode *left, *right;    TreeNode(int v) : data(v), left(NULL), right(NULL) {}};int checkHeight(TreeNode *node) {    if (node == NULL) {        return 0;    }        int leftHeight = checkHeight(node->left);    if (leftHeight == -1) {        return -1;    }        int rightHeight = checkHeight(node->right);    if (rightHeight == -1) {        return -1;    }        if (abs(leftHeight - rightHeight) > 1) {        return -1;    } else {        return max(leftHeight, rightHeight) + 1;    }}bool isBalanced(TreeNode *node) {    return checkHeight(node) != -1;}

原创粉丝点击