Home | Projects | Notes > Problem Solving > LC - E - 257. Binary Tree Paths (DFS)
This solution uses Depth-First Search (DFS) algorithm and recursion.
Be able to introduce and use new members to the Solution class (e.g., helper functions, variables, etc.)
Complexity Analysis:
Solution:
xxxxxxxxxx
451/**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 * };
11 */
12class Solution {
13public:
14 vector<string> binaryTreePaths(TreeNode* root) {
15 string s; // will be used to build up each path
16 buildPath(root, s);
17 return paths;
18 }
19
20private:
21 vector<string> paths;
22
23 // helper function
24 void buildPath(TreeNode *root, string s)
25 {
26 // if root does not exist (termination condition 1)
27 if (!root)
28 return;
29 // if root is a leaf (termination condition 2)
30 else if (root->left == root->right) // (!root->left && !root->right)
31 {
32 s += to_string(root->val);
33 paths.push_back(s);
34 }
35 // if root is a not a leaf
36 else
37 {
38 s = s + to_string(root->val) + "->";
39
40 // recursive step
41 buildPath(root->left, s);
42 buildPath(root->right, s);
43 }
44 }
45};