Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]
#include <iostream>
#include <string>
#include <vector>

using namespace std;


struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	
	
};


struct TreeNode *newNode(int data)
{
	struct TreeNode *node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
	node->val = data;
	node->left = NULL;
	node->right = NULL;
	return (node);
}
class Solution {
public:
	vector<string> res;
	string s;
	vector<string> binaryTreePaths(TreeNode* root)
	{
		if (root == NULL)
			return res;

		if (!root->left&& !root->right)
		{
			s.append(to_string(root->val));
			res.push_back(s);
			return res;
		}

		help_paths(root, s, res);

		return res;

	}

	void help_paths(TreeNode *root, string &s, vector<string> &res)
	{
		if (root->left == NULL && root->right == NULL)
		{
			s.append(to_string(root->val));
			res.push_back(s);
			return;
		}

		s.append(to_string(root->val));
		s.push_back('-');
		s.push_back('>');
		if (root->left)
		{
			
			help_paths(root->left, s, res);
			int i = s.size() - 1;
			for (; i >= 0; i--)
			{
				if (s[i] == '>')
					break;
			}
			if (i+1<s.size())
			s.erase(s.begin()+1+i, s.end());
		}
		if (root->right)
		{
			
			help_paths(root->right, s, res);
			int j = s.size() - 1;
			
			for (; j >= 0; j--)
			{
				if (s[j] == '>')
				{
						break;
				}
			}
			if (j + 1<s.size())
			s.erase(s.begin()+1+j, s.end());
		}
		
		int j = s.size() - 1;
		int count = 0;
		for (; j >= 0; j--)
		{
			if (s[j] == '>')
			{
				count++;
				if (count==2)
				break;
			}
		}
		if (j + 1<s.size())
			s.erase(s.begin() + 1 + j, s.end());
		return;

	}
};


int main(int argc, char *argv[])
{

	struct TreeNode *root = newNode(1);
	root->left = newNode(2);
	root->right = newNode(3);
	root->left->left = newNode(4);
	root->left->right = newNode(7);

	vector<string> m;
	Solution test;
	m=test.binaryTreePaths(root);
	
	for (int i = 0; i < m.size(); ++i)
	{
		cout << m[i] << endl;
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值