563. Binary Tree Tilt
来源:互联网 发布:linux 复制vi中的内容 编辑:程序博客网 时间:2024/06/11 05:08
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 3Output: 1Explanation: Tilt of node 2 : 0Tilt of node 3 : 0Tilt of node 1 : |2-3| = 1Tilt 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.
官方解答:
Approach #1 Using Recursion [Accepted]
Algorithm
From the problem statement, it is clear that we need to find the tilt value at every node of the given tree and add up all the tilt values to obtain the final result. To find the tilt value at any node, we need to subtract the sum of all the nodes in its left subtree and the sum of all the nodes in its right subtree.
Thus, to find the solution, we make use of a recursive function traverse
which when called from any node, returns the sum of the nodes below the current node including itself. With the help of such sum values for the right and left subchild of any node, we can directly obtain the tilt value corresponding to that node.
Approach #1 Using Recursion [Accepted]
Algorithm
From the problem statement, it is clear that we need to find the tilt value at every node of the given tree and add up all the tilt values to obtain the final result. To find the tilt value at any node, we need to subtract the sum of all the nodes in its left subtree and the sum of all the nodes in its right subtree.
Thus, to find the solution, we make use of a recursive function traverse
which when called from any node, returns the sum of the nodes below the current node including itself. With the help of such sum values for the right and left subchild of any node, we can directly obtain the tilt value corresponding to that node.
- 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
- 《算法》介绍和pdf下载
- C++操作mysql数据库
- 类的一般形式和构造器+类的继承
- 【设计模式】设计模式六大原则
- php imagecreate调用imagecolorallocate无法改变颜色
- 563. Binary Tree Tilt
- 发邮件报错:smtp.SMTPSendFailedException: 553 Mail from must equal authorized user=发件人邮箱写错
- java的native方法和JNI
- (c语言总结)关于一些简单的区别
- Oracle之DBMS_STATS.GATHER_TABLE_STATS详解
- Error: Can't find Python executable "python", you can set the PYTHON env variable.解决办法
- Java 实现生产者消费者问题
- mybatis的简单使用过程
- 8种排序方式