树、递归————二叉树的所有路径

递归终止条件:到达叶子节点,即该节点的左右孩子均为空。 
路径的拼接:每个节点值 + -> + 左孩子的路径/右孩子的路径(左右均可能有多个路径)

 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         vector<string> res;
14         if(root == NULL) return res;
15         if(root->left == NULL && root->right == NULL)
16             res.push_back(to_string(root->val));
17         //不是叶子节点的话
18         vector<string> leftS = binaryTreePaths(root->left);
19         for(int i = 0; i < leftS.size(); i ++)
20             res.push_back(to_string(root->val) + "->" + leftS[i]);
21         vector<string> rihgtS = binaryTreePaths(root->right);
22         for(int i = 0; i < rihgtS.size(); i ++)
23             res.push_back(to_string(root->val) + "->" + rihgtS[i]);
24         return res;
25     }
26 };

 

posted @ 2019-06-24 11:09  Austin_anheqiao  阅读(322)  评论(0编辑  收藏  举报