Related topics
Topic Link
LeetCode China, https://leetcode-cn.com/problems/binary-tree-paths/ . Note need to log in.
Title Description
Given a binary tree, all paths from the root node to return leaf nodes.
Description: leaf node is a node has no child nodes.
Examples
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
Topic analysis
Analysis of the meaning of problems
To a binary tree, starting from the root node, respectively, to find a binary tree left subtree and right subtree.
Sample data analysis
Can be seen, the input data is a root node. We first traverse the left subtree, that is 2. From node 2, continue to traverse the left subtree, since the left sub-tree does not exist, then traverse the right subtree, we came to the node 5. Because 5 is a leaf node, and thus with the left subtree of a node traversal path 1-> 2-> 5. Back to the root node. This time we traverse the right subtree, went 3. Since 3 is a leaf node, the traversal path with the right child node is 1-> 3.
Algorithm thinking
LeetCode given the difficulty of the problem is simple. We can use DFS to solve this problem.
Search termination condition
The current node is empty. code show as below:
if (NULL==root) {
return;
}
Search function parameters
1, the root node, a node representing the current operation.
2, a string that represents the starting node to the path traversed from the root node.
Accordingly prototype DFS () function is as follows:
void dfs(TreeNode* root, string path);
Note that the second parameter path references can not be used as a reference will preserve the original data. After completion will lead to traverse the left subtree, traverse the right subtree when the left sub-tree data is still preserved.
Start calling way
You can call directly from the root node.
string path;
dfs(root, path);
Backtracking
You do not need.
Algorithm steps
1, starting from the current node.
2, if the current node is empty (NULL), then the function returns DFS.
3, the current node is not empty, the value of the node is added to the traversal process.
4, recursively traverse the left subtree of the current node.
5, recursively traverse right subtree of the current node.
AC reference code
/**
* 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> ans;
vector<string> binaryTreePaths(TreeNode* root) {
string path;
dfs(root, path);
return ans;
}
void dfs(TreeNode* root, string &path) {
//返回条件
if (NULL==root) {
return;
}
//加入自己
if (path.size()) {
path += "->";
}
path += to_string(root->val);
//如果是叶子结点,加入答案
if (NULL==root->left && NULL==root->right) {
ans.push_back(path);
} else {
//左子树
dfs(root->left, path);
//右子树
dfs(root->right, path);
}
}
};