[LeetCode] Binary Tree Paths

257. Binary Tree Paths

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<string> res;
void helper(TreeNode* node, string path) {
if(!node->left and !node->right) res.push_back(path);
else {
if(node->left) helper(node->left, path + "->" + to_string(node->left->val));
if(node->right) helper(node->right, path + "->" + to_string(node->right->val));
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return {};
helper(root, to_string(root->val));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/28/PS/LeetCode/binary-tree-paths/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.