【树】257. 二叉树的所有路径

题目:

解法:

基本思路是每次访问到叶子节点的时候,将已有的路径进行输出,可以用一个栈来存储,每次回溯的时候,节点出栈,然后访问至叶子节点时,对栈结构进行遍历即可,这里采用vector进行操作,其优势在于,可以直接采用下标进行访问!

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<string> binaryTreePaths(TreeNode* root) 
13     {
14         if(root==nullptr)
15         {
16             return res;
17         }
18 
19         //遍历,直到叶子节点
20         vector<int> a;
21         dfs(root,a);
22         return res;
23     }
24 
25     void dfs(TreeNode* root,vector<int> &a)
26     {
27         if(root==nullptr)
28         {
29             return;
30         }
31 
32         //cout<<root->val<<endl;
33         a.push_back(root->val);
34         
35         if(root->left!=nullptr)
36         {
37             dfs(root->left,a);
38         }
39         
40         if(root->right!=nullptr)
41         {
42             dfs(root->right,a);
43         }
44         
45         //此时为叶子节点
46         if(root->left==nullptr && root->right==nullptr)
47         {
48             storeRes(a,res);
49         }
50         a.pop_back();  //弹出一个元素
51 
52         return;
53     }
54 
55     void storeRes(vector<int> vc,vector<string> &res)
56     {
57         //函数功能:将vc中int类型的数字连接成字符串,存入res中
58         string s="";
59         for(int i=0;i<vc.size();i++)
60         {
61             if(i==vc.size()-1)
62                 s+=(to_string(vc[i])+"");
63             else
64                 s+=(to_string(vc[i])+"->");
65         }
66         //cout<<"string s is "<<s<<endl;
67         res.push_back(s);
68     }
69 private:
70     vector<string> res;
71 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12818438.html