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);}
阅读全文
0 0
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt **
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- 563. Binary Tree Tilt
- LeetCode 563. Binary Tree Tilt
- LeetCode | 563. Binary Tree Tilt
- [LeetCode]563. Binary Tree Tilt
- 一些软件思想
- Javascript的对象及原型
- virtualenv+nginx+uwsgi+django配置
- 重构优化
- Mysql面试总结
- 563. Binary Tree Tilt
- 高三志
- EditText绑定键盘监听事件
- eclipse中将mavenweb项目部署到tomcat中
- 一道小米的笔试题
- window线程池
- Java常用并发容器(concurrent包)
- 【操作系统学习日记】1.环境安装(ubantu+bochs)
- derby数据库源码分析(三)–页面分析