题目
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点
官方解法
这种找路径的题都跟深度优先搜索有关系,其本质的思想是递归,就是用一个函数来套他本身,使得不断得到树的子节点,直到叶子结点。
官方代码
class Solution {
public:
void construct_paths(TreeNode* root, string path, vector<string>& paths) {
if (root != nullptr) {
path += to_string(root->val);
if (root->left == nullptr && root->right == nullptr) { // 当前节点是叶子节点
paths.push_back(path); // 把路径加入到答案中
} else {
path += "->"; // 当前节点不是叶子节点,继续递归遍历
construct_paths(root->left, path, paths);
construct_paths(root->right, path, paths);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
construct_paths(root, "", paths);
return paths;
}
};
个人思路
整体思路与答案相同,本人的解法借鉴了另一篇文章 :
添加链接描述
这篇文章较为整体的描述了各种路径的问题,值得一看。
个人代码
bool test(string s, vector& wordDict) {
string a;
/**
* 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 {
public:
vector<string> res;
vector<string> binaryTreePaths(TreeNode* root) {
dfs(root, "");
return res;
}
void dfs(TreeNode* root, string path){ //函数dfs
if(!root) return;
path += to_string(root->val);
if(!root->left && !root->right){
res.push_back(path);
return;
}
dfs(root->left,path+"->"); //第一个dfs
dfs(root->right,path+"->"); //第二个dfs
}
};
思考
在函数dfs中,其套用的dfs分别为遍历其左孩子和又孩子的递归,因此在这一位置加入“->”。
在我初次测试时候,输入的为“ path+=‘->’ ”,其输出结果最后一个节点会为两个->
原因是运行到第一个dfs时候path 加入了一个->, 此时的path在整个全局都改变了,再运行到第二个dfs时候会再次加入“->”。
去掉=号,变为path+“->”时,表示为仅仅传参进入第一个dfs的path加入了“->”,对第二个dfs无影响。此时能够得到正确答案。