Leetcode 257 Binary Tree Paths 二叉树 DFS

找到所有根到叶子的路径

深度优先搜索(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> vs_;
13     void dfs(TreeNode* root, string s){
14         if(!root) return;
15         if(!root->left && !root->right){
16            char t[20] = "";
17            sprintf(t, "->%d", root->val);
18            vs_.push_back(s + string(t));
19            return;
20         }
21         else{
22            char t[20] = "";
23            sprintf(t, "->%d", root->val);
24            dfs(root->left, s + string(t));
25            dfs(root->right, s + string(t));
26         }
27     }
28     vector<string> binaryTreePaths(TreeNode* root) {
29         vs_.clear();
30         if(!root) return vs_;
31         char t[20] = "";
32         sprintf(t, "%d", root->val);
33         string s(t);
34         if(!root->left && !root->right){
35             vs_.push_back(s);
36             return vs_;  
37         } 
38         dfs(root->left, s);
39         dfs(root->right, s);
40         return vs_;
41     }
42 };

 

posted @ 2016-03-18 20:30  Breeze0806  阅读(150)  评论(0编辑  收藏  举报