[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
原创粉丝点击