LeetCode 257 二叉树的所有路径

时间:2023-03-10 02:08:16
LeetCode 257 二叉树的所有路径

题目:

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

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
/ \
2 3
\
5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

解题思路:

递归,在参数列表里回溯的方法灰常好用,这里介绍两种方法。

代码:

法一:

/**
* 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> ans;
if(root == NULL)
return ans;
if(!root->left && !root->right)
ans.push_back(to_string(root->val));
vector<string> leftSub = binaryTreePaths(root->left);
for(int i=; i<leftSub.size(); ++i)
ans.push_back(to_string(root->val) + "->" + leftSub[i]);
vector<string> rightSub = binaryTreePaths(root->right);
for(int i=; i<rightSub.size(); ++i)
ans.push_back(to_string(root->val) + "->" + rightSub[i]);
return ans;
}
};

参考来源https://blog.****.net/my_clear_mind/article/details/82283939

法二:

 /**
* 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 DFS(TreeNode* root, string temp, vector<string> &ans)
{
if(root == NULL) {
return ;
}
if(root->left == NULL && root->right == NULL) {
temp += to_string(root->val);
ans.push_back(temp);
return ;
}
if(root->left) {
DFS(root->left, temp + to_string(root->val) + "->", ans);
}
if(root->right) {
DFS(root->right, temp + to_string(root->val) + "->", ans);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ans;
if(root == NULL)
return ans;
DFS(root, "", ans);
return ans;
}
};