博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode C++ 563. Binary Tree Tilt【Tree/DFS】简单
阅读量:2005 次
发布时间:2019-04-28

本文共 1292 字,大约阅读时间需要 4 分钟。

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.

题意:给定一个二叉树,计算整个树的坡度。


思路 递归后序遍历

注意:一个二叉树的节点坡度定义为,该节点左子树的结点值之和右子树结点值之和绝对值。空结点的的坡度是 0 。题目要求出整个树的坡度,就是所有节点的坡度之和。递归后序遍历的代码如下:

class Solution {
public: int findTilt(TreeNode* root) {
int tilt = 0; postorder(root, tilt); return tilt; } int postorder(TreeNode *root, int &tilt) {
//返回子树的值之和 if (!root) return 0; if (!root->left && !root->right) return root->val; int lsum = postorder(root->left, tilt); int rsum = postorder(root->right, tilt); tilt += abs(lsum - rsum); return root->val + lsum + rsum; }};

效率较低:

执行用时:32 ms, 在所有 C++ 提交中击败了67.95% 的用户内存消耗:23.2 MB, 在所有 C++ 提交中击败了30.93% 的用户

转载地址:http://hlotf.baihongyu.com/

你可能感兴趣的文章
curl_easy_getinfo() -- 从 curl 句柄里获得附加信息
查看>>
初次使用Qt Creater网络编程,出现error: undefined reference to `_imp__WSAStartup@8'
查看>>
vs2010下release版本调试设置
查看>>
Windows共享内存示例
查看>>
多线程之线程通信
查看>>
windows C++进程间和线程间通信
查看>>
Windows线程同步(一):临界区对象
查看>>
秒杀多线程第十篇 生产者消费者问题
查看>>
秒杀多线程第一篇 多线程笔试面试题汇总
查看>>
进程间同步互斥经典问题(一)生产者-消费者问题
查看>>
线程同步-生产者消费者问题
查看>>
C++之线程信号量机制
查看>>
array学习之创建,初始化,赋值操作get, empty,size
查看>>
Qt队列下载文件
查看>>
现代C++学习笔记——第2章
查看>>
qt读写xml文件
查看>>
Qt删除文件和文件夹
查看>>
使用开源库zlib压缩和解压文件
查看>>
Qt中用QuaZip来压缩和解压缩文件
查看>>
Qt实现zip压缩和解压,编译、调用zlib和QuaZip动态库过程详解
查看>>