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 };

 

转载于:https://www.cnblogs.com/onlyac/p/5293468.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值