写在前面
题目详情
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
ac代码
- 解题思想
- 递归迭代
for
循环逆序拼装(左右均可能有多个路径)
递归迭代变量、数组值/大小关系!!!
方法1:
递归先左后右
class Solution
{
public:
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string> ans;
if(!root)
return ans;
if(root->left == NULL && root->right == NULL)
ans.push_back(to_string(root->val));
vector<string> leftS = binaryTreePaths(root->left);
for(int i=0; i<leftS.size(); i++)
ans.push_back(to_string(root->val) + "->" + leftS[i]);
vector<string> rightS = binaryTreePaths(root->right);
for(int i=0; i<rightS.size(); i++)
ans.push_back(to_string(root->val) + "->" + rightS[i]);
return ans;
}
};
方法2:
深度优先搜索(Depth-First-Search
)
class Solution
{
private:
vector<string> ans;
public:
vector<string> binaryTreePaths(TreeNode* root)
{
if(!root)
return ans;
dfs(root, to_string(root->val));
return ans;
}
void dfs(TreeNode* root, string str)
{
if (root->left == NULL && root->right == NULL)
{
ans.push_back(str);
return;
}
if(root->left != NULL)
dfs(root->left, str + "->" + to_string(root->left->val));
if(root->right != NULL)
dfs(root->right, str + "->" + to_string(root->right->val));
}
};