0%

binary-tree-paths

Binary Tree Paths – LeetCode 257

Problem

Description

Given a binary tree, return all root-to-leaf paths.

Answer

Original

Code

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> Path(TreeNode* root, string s){
s += "->" + to_string(root->val);
if(root->left == root->right) return vector<string>({s});
vector<string> v_s, tmp;
if(root->left) {
tmp = Path(root->left,s);
v_s = std::move(tmp);
}
if(root->right) {
tmp = Path(root->right,s);
v_s.insert(v_s.end(),tmp.begin(),tmp.end());
}
return v_s;
}

vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return vector<string>();
if(root->left != root->right){
vector<string> v_s, tmp;
if(root->left) {
tmp = Path(root->left,to_string(root->val));
v_s = std::move(tmp);
}
if(root->right) {
tmp = Path(root->right,to_string(root->val));
v_s.insert(v_s.end(),tmp.begin(),tmp.end());
}
return v_s;
} else
return vector<string>({to_string(root->val)});
}
};

思路

使用递归依次遍历然后添加元素,时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$6$ ms,排名$85.23\%$

Better

思路

写的更漂亮,但是并非纯函数,存在性能优化,时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$6$ ms,排名$85.23\%$

Code

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(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void binaryTreePaths(vector<string>& result, TreeNode* root, string t) {
if(root->left == root->right) {
result.push_back(t);
return;
}
if(root->left) binaryTreePaths(result, root->left, t + "->" + to_string(root->left->val));
if(root->right) binaryTreePaths(result, root->right, t + "->" + to_string(root->right->val));
}

vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if(!root) return result;
binaryTreePaths(result, root, to_string(root->val));
return result;
}
};