leetcode 257. Binary Tree Paths

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

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

思路:回溯(dfs)

 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         string s = "";
15         dfs(root, res, s);
16         return res;
17     }
18 private:
19     void dfs(TreeNode *root, vector<string> &res, string s) {
20         if (root == NULL)
21             return;
22         s += to_string(root->val);
23         if (root->left == NULL && root->right == NULL) {
24             res.push_back(s);
25             return;
26         }
27         if (root->left != NULL)
28             dfs(root->left, res, s + "->");
29         if (root->right != NULL)
30             dfs(root->right, res, s + "->");
31         s.pop_back();
32     }
33 };

 

posted @ 2019-08-30 09:47  琴影  阅读(223)  评论(0编辑  收藏  举报