首页 > 其他 > 详细

Leetcode 257 Binary Tree Paths 二叉树 DFS

时间:2016-03-18 21:42:11      阅读:146      评论:0      收藏:0      [点我收藏+]

找到所有根到叶子的路径

深度优先搜索(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 };

 

Leetcode 257 Binary Tree Paths 二叉树 DFS

原文:http://www.cnblogs.com/onlyac/p/5293468.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!