[LeetCode]257. Binary Tree Paths

Problem

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

Note: A leaf is a node with no children.

1
2
3
4
5
6
7
8
9
10
11
12
13
Example:

Input:

1
/ \
2 3
\
5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

给定一颗二叉树,返回所有从根节点到叶子节点的路径.

Solution

Analysis

这道题本质上是在考二叉树的前序遍历.其他字符串处理是小枝节. 二叉树的前序遍历:根左右. 最常用的方法递归. 这里需要对遍历结果进行处理,当遍历到叶子节点时,说明找到一条路径,将这条路径保存到结果数组中;其他情况,继续遍历.

处理”->”, 将最后的叶子节点单独处理, 其他情况遍历完,同时加上”->”.

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
/**
* 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> binaryTreePaths(TreeNode* root) {
vector<string> result;
if (!root) return result;
string path = "";

preorder(root, path, result);

return result;
}
private:
void preorder(TreeNode* root, string path, vector<string>& result){
if (!root->left && !root->right){
path += to_string(root->val);
result.push_back(path);
return;
}
path += to_string(root->val) + "->";
if (root->left) preorder(root->left, path, result);
if (root->right) preorder(root->right, path, result);
}
};
您的支持就是我更新的最大动力!谢谢!