257. 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"]
答案:
和遍历类似,用递归的思路,深度优先搜索的算法
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>str; 14 if(root==NULL){ 15 return str; 16 } 17 DFS(root,"",str); 18 return str; 19 } 20 void DFS(TreeNode *node,string temp, vector<string>&str){ 21 if(node->left==NULL&&node->right==NULL){ 22 str.push_back(temp+to_string(node->val)); 23 } 24 if(node->left!=NULL){ 25 DFS(node->left,temp+to_string(node->val)+"->",str); 26 } 27 if(node->right!=NULL){ 28 DFS(node->right,temp+to_string(node->val)+"->",str); 29 } 30 } 31 };