Leetcode 257 Binary Tree Paths 二叉树 DFS

Posted 我没货,只剩下水了

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };

 

以上是关于Leetcode 257 Binary Tree Paths 二叉树 DFS的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 257. Binary Tree Paths

Java [Leetcode 257]Binary Tree Paths

leetcode?python 257. Binary Tree Paths

leetcode 257. Binary Tree Paths

Leetcode 257: Binary Tree Paths

Leetcode 257. Binary Tree Paths