[LeetCode] Sum of Left Leaves 左叶子节点的和
来源:互联网 发布:.cn域名可以过户吗? 编辑:程序博客网 时间:2024/06/08 10:58
声明:原题目转载自LeetCode,解答部分为原创
Problem :
Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
Solution:
思路:遍历树的所有节点,本次选用中序遍历方法,判断叶子节点为左叶子节点的条件是:1、父节点的左子节点;2、左右子节点皆为空,将所有左叶子节点的值相加并返回。
代码如下:
#include<iostream>#include<stack>using namespace std;// 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:void travel_record(TreeNode* root){while(!left_leaf.empty())left_leaf.pop();//int last_step = -1;int left_num = 0;route.push(root);while( !route.empty() ){TreeNode* temp = route.top();route.pop();if(temp->left != NULL){route.push(temp->left);//last_step = 0;if(temp->left->left == NULL && temp->left->right == NULL)left_leaf.push(temp->left->val);}if(temp->right != NULL){//last_step = 1;route.push(temp->right);}}} int sumOfLeftLeaves(TreeNode* root) { if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return 0; travel_record(root); int size = left_leaf.size(); int result = 0; for(int i = 0 ; i < size ; i ++ ){int temp = left_leaf.top(); result += temp;left_leaf.pop();}return result; } private:stack<int> left_leaf;stack<TreeNode* > route;};int main(){TreeNode* root = new TreeNode(3);TreeNode* node_1 = new TreeNode(9);TreeNode* node_2 = new TreeNode(20);root->left = node_1;root->right = node_2;TreeNode* node_3 = new TreeNode(15);TreeNode* node_4 = new TreeNode(7);node_2->left = node_3;node_2->right = node_4;Solution text;cout << text.sumOfLeftLeaves(root) << endl;return 0;}
0 0
- [LeetCode] Sum of Left Leaves 左叶子节点的和
- Leetcode 404. Sum of Left Leaves 左叶子节点的和 解题报告
- leetcode-404. Sum of Left Leaves 求左叶子节点的和,递归
- 404. Sum of Left Leaves求树的所有左叶子节点的和
- leetcode_404. Sum of Left Leaves-左叶子的和
- [LeetCode]404. Sum of Left Leaves(叶子结点的和)
- 【LeetCode】Sum of Left Leaves 左叶子之和
- 404. Sum of Left Leaves | 所有左子树的和
- Sum of Left Leaves ---LeetCode
- Leetcode Sum of Left Leaves
- LEETCODE--Sum of Left Leaves
- LeetCode : Sum of Left Leaves
- leetcode- Sum of Left Leaves
- LeetCode Sum of Left Leaves
- [LeetCode]404. Sum of Left Leaves 树的典型题目
- LeetCode笔记:404. Sum of Left Leaves
- 【leetcode】404. Sum of Left Leaves【E】
- LeetCode—404. Sum of Left Leaves
- 基于Arduino的多功能数字时钟
- MRI影像学习笔记(五.完结)
- 最大映射
- 【可信计算】可信计算学习研究资源整理
- 一些不错的博客
- [LeetCode] Sum of Left Leaves 左叶子节点的和
- java中Scanner
- A003-算法-滑动窗口队列(未测试)
- windows tcp buffer size 调研
- 3、类和接口
- BZOJ3211 花神游历各国 线段树+并查集
- <模型汇总-5>开山鼻祖-深度信念网络DBN
- Java多线程编程总结
- <转载>名言