Esempio n. 1
0
 bool checkBalanced(TreeNode *root, int &height){
     if(root == NULL) return true;
     
     int lh, rh;
     int result = true;
     if(root->left != NULL)
     {
         result &= checkBalanced(root->left, lh);
     }
     else
     {
         lh = -1;
     }
     
     if(root->right != NULL)
     {
         result &= checkBalanced(root->right, rh);
     }
     else
     {
         rh = -1;
     }
     
     height = 1 + max(lh, rh);
     
     if(lh - rh >= -1 && lh - rh <= 1) return result;
     else return false;
 }
Esempio n. 2
0
int main(int argc, char* argv[]) {

    int debuggingMode = 0;
    StackPtr stack; //the pointer to the stack for chars
    stack = stk_create(); //create the stack

    if(argv[1] != NULL) {
        if(strcmp(argv[1], "-d\n")) {
            debuggingMode = 1;
        }
    }

    char input[300]; //assuming input will be less than 300 characters
    int comp;

    //Ask the user for input
    printf("Enter symbols you'd like checked for balance or Q to quit: ");
    fgets(input, 300, stdin);

   while(strcmp("Q\n", input) != 0 && strcmp("q\n", input) != 0) {

        checkBalanced(stack, input, debuggingMode);

        stk_clear(stack);

        printf("Enter symbols you'd like checked for balance or Q to quit: ");
        fgets(input, 300, stdin);

    }

    return 0;
}
Esempio n. 3
0
void ex4_1() {
    std::cout << "ex4.1 \n";
    TreeNode<int> a {15, nullptr, nullptr};
    TreeNode<int> b {10, &a, nullptr };
    TreeNode<int> c {5, nullptr, nullptr };
    TreeNode<int> d {3, &b, &c };
    std::pair<bool, int> res { checkBalanced(&d) };
    std::cout << " is the tree balanced? " << res.first << std::endl;
}
Esempio n. 4
0
std::pair<bool, int> checkBalanced(TreeNode<T>* root) {
//    std::cout << "at " ; root->print();
    std::pair<bool, int> recurseLeft {false, 0};
    std::pair<bool, int> recurseRight {false, 0};
    if (root->right)
        recurseRight = checkBalanced(root->right);
    if (root->left)
        recurseLeft = checkBalanced(root->left);
    if (!recurseLeft.first || !recurseRight.first) {
  //      std::cout << " some sub-tree is unbalanced " << std::endl;
        return std::make_pair(false, 0);
    }
    if (abs(recurseLeft.second - recurseRight.second) > 1) {
    //    std::cout << " one sub-tree is much higher than the other ";
        return std::make_pair(false, 0);
    }
    int max_height {std::max(recurseRight.second, recurseLeft.second) + 1};
    //std::cout << " node is balanced, max height of the sub-trees is " << max_height << " ";
    return std::make_pair(true, max_height);
}
Esempio n. 5
0
 bool isBalanced(TreeNode *root) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     int height;
     return checkBalanced(root, height);
 }