257二叉树的所有路径(递归、非递归)

1、题目描述

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

2、示例

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

3、题解

基本思想:递归

#include<iostream>
#include<vector>
#include<unordered_map>
#include<string>
#include<algorithm>
using namespace std;
struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#define inf 9999
void Init_TreeNode(TreeNode** T, vector<int>& vec, int& pos)
{
	if (vec[pos] == inf || vec.size() == 0)
		*T = NULL;
	else
	{
		(*T) = new TreeNode(0);
		(*T)->val = vec[pos];
		Init_TreeNode(&(*T)->left, vec, ++pos);
		Init_TreeNode(&(*T)->right, vec, ++pos);
	}
}
class Solution {
public:
	vector<string> res;
	vector<string> binaryTreePaths(TreeNode* root) {
		//基本思想:递归
		if (root == nullptr)
			return res;
		string s;
		dfs(root, s);
		return res;
	}
	void dfs(TreeNode* root, string s)
	{
		if (root->left == nullptr && root->right == nullptr)
		{
			s.append(to_string(root->val));
			res.push_back(s);
			return;
		}
		s.append(to_string(root->val));
		s.append("->");
		if (root->left != nullptr)
		{
			dfs(root->left, s);
		}
		if (root->right != nullptr)
		{
			dfs(root->right, s);
		}
		return;
	}
};
class Solution1 {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
		//非递归
        stack<TreeNode*> st;
        stack<string> path;
        vector<string> res;
        string cur;
        if(root)
        {
            st.push(root);
            path.push(to_string(root->val));
        }    
        while(!st.empty())
        {
            root=st.top();
            st.pop();
            cur=path.top();
            path.pop();
            if(root->left==nullptr&&root->right==nullptr)
                res.push_back(cur);
            if(root->left)
            {
                st.push(root->left);
                path.push(cur+"->"+to_string(root->left->val));
            }
            if(root->right)
            {
                st.push(root->right);
                path.push(cur+"->"+to_string(root->right->val));
            }
        }
        return res;
    }
};
int main()
{
	Solution solute;
	TreeNode* root = NULL;
	vector<int> vec = { 5,-13,-2,-1,inf,inf,inf,4,inf,inf,6,inf,inf };
	int pos = 0;
	Init_TreeNode(&root, vec, pos);
	vector<string> res = solute.binaryTreePaths(root);
	for_each(res.begin(), res.end(), [](const string v) {cout << v << endl; });
	return 0;
}

 

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值