563. Binary Tree Tilt

来源:互联网 发布:安卓ar软件 编辑:程序博客网 时间:2024/06/10 19:07
  • Given a binary tree, return the tilt of the whole tree.

    The tilt of a tree node is defined as the absolute difference between
    the sum of all left subtree node values and the sum of all right
    subtree node values. Null node has tilt 0.

    The tilt of the whole tree is defined as the sum of all nodes’ tilt.

    Example: Input:
    1
    / \
    2 3
    Output: 1 Explanation: Tilt of node 2 : 0 Tilt of node 3 : 0 Tilt of node 1 : |2-3| = 1 Tilt of binary tree : 0 + 0 + 1 = 1
    Note:

    The sum of node values in any subtree won’t exceed the range of
    32-bit integer. All the tilt values won’t exceed the range of 32-bit
    integer.

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */struct TreeNode * creatSumTree(struct TreeNode *root){      struct TreeNode * newNode = NULL;    if(root == NULL){        return NULL;    }else{        newNode = (struct TreeNode * )malloc(sizeof(struct TreeNode));        newNode->left = NULL;        newNode->right = NULL;        newNode->val = 0;        if(root->left == NULL &&           root->right == NULL){            newNode->val = root->val;        }else{            newNode->left = creatSumTree(root->left);            newNode->right = creatSumTree(root->right);            newNode->val = root->val;            if(newNode->left){                newNode->val += newNode->left->val;            }            if(newNode->right){                newNode->val += newNode->right->val;            }        }        return  newNode;            }}int calculateTreeTilt(struct TreeNode* root){    int tilt = 0;    if(root == NULL){        return 0;    }    if(root->left){        tilt += root->left->val;    }       if(root->right){        tilt -= root->right->val;    }    tilt = abs(tilt);    tilt = tilt + calculateTreeTilt(root->left) + calculateTreeTilt(root->right);    return tilt;}void printTree(struct TreeNode* root){    if(root == NULL){        printf(" null \n\r");        return;    }else{        printf(" %d ",root->val);        printf("\n\r");        printTree(root->left);        printTree(root->right);        printf("\n\r");    }}int findTilt(struct TreeNode* root) {    struct TreeNode * sumTree = creatSumTree(root);    //printTree(sumTree);    return calculateTreeTilt(sumTree);}
原创粉丝点击