[LeetCode] Sum of Left Leaves 左叶子节点的和

声明:原题目转载自LeetCode,解答部分为原创

Problem :

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值