leetcode-404-Sum of Left Leaves
来源:互联网 发布:自制mac安装盘 编辑:程序博客网 时间:2024/06/04 19:23
问题
题目:[leetcode-404]
思路
这个题刚开始想用递归写,一时每反应过来。
然后想层次遍历,一时又没反应过来。
其实,基本的算法还是遍历。层次遍历即可,但是只要左叶子。
所以,我考虑加标签,主要是想模仿线索二叉树。然后写了一个结构,加了是左孩子右孩子的标签。问题搞定。
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /* 既然你只有左叶子才要计算,所以给左叶子一个标记。出队的时候判断一下,如果是左叶子。 那么计数,否则不计数。 */struct element{ TreeNode* root_; int flag_; element( TreeNode* r, int flg ) : root_(r), flag_(flg) // 1 for left, 2 for right {}};class Solution {public: int sumOfLeftLeaves(TreeNode* root) { if(!root) return 0; int ans = 0; std::queue<element> q; q.push( element(root, -1) ); while( !q.empty() ){ element e = q.front(); q.pop(); if( !e.root_->left && !e.root_->right ) { if( 1 == e.flag_ ) ans += e.root_->val; } if( e.root_->left ) { q.push( element( e.root_->left, 1 ) ); } if( e.root_->right ) { q.push( element( e.root_->right, 2 ) ); } }// while return ans; }};
思路
本质既然是便利,深度和广度应该是都可以做成这件事情的。其实深度的做法一样,加入左右标志即可。根节点需要特殊处理。
代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int sumOfLeftLeaves(TreeNode* root) { int ans = 0; preOrder( root, 0, ans ); return ans; }private: void preOrder(TreeNode* root, int flag, int& ans){ if(!root) return; if( !root->left && !root->right && 1==flag ) ans += root->val; preOrder( root->left, 1, ans ); preOrder( root->right, 2, ans ); }};
0 0
- LeetCode 404 Sum of Left Leaves
- [LeetCode-404]Sum of Left Leaves(java)
- Leetcode 404 Sum of Left Leaves
- LeetCode[404] Sum of Left Leaves
- LeetCode #404: Sum of Left Leaves
- LeetCode 404 Sum of Left Leaves (DFS)
- leetcode 404 Sum of Left Leaves
- LeetCode #404 - Sum of Left Leaves - Easy
- leetcode 404 Sum of Left Leaves C++
- leetcode-404-Sum of Left Leaves
- leetcode 404 Sum of Left Leaves
- [Leetcode] #404 Sum of Left Leaves
- Leetcode #404 Sum of Left Leaves
- LeetCode 404:Sum of Left Leaves
- LeetCode 404 Sum of Left Leaves
- Sum of Left Leaves ---LeetCode
- Leetcode Sum of Left Leaves
- LEETCODE--Sum of Left Leaves
- Java 反射
- OpenCV入门教程(8)-视频文件的读取和存储
- opencv学习(二十五)之开运算、闭运算、形态梯度、顶帽、黑帽
- php+二维码图片生成封装成对象类
- network_questions
- leetcode-404-Sum of Left Leaves
- android.support.v7.app.AlertDialog 使用报错
- 帮你理解学习lambda式
- http://www.cnblogs.com/GnagWang/archive/2011/03/31/2001067.html
- Windows和Linux下安装JDK
- C# 学习之旅(二)简单的继承多态介绍
- maomao
- 【JAVA开发】JadClipse安装和配置
- 2017.01.16 学习日记-享元模式