今天刷了一道题,感觉编程思路还是有些绕,下面就和大家分享一下经验吧!
题目如下:
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
题意分析:
给定一个二叉树,请返回所有从根节点到叶子节点的路径。
方法一(递归法)
分别对根节点的左右子树进行递归调用,将两部分递归所得的路径结果直接与根节点值拼接得到所有从根节点到叶子节点的路径。其中递归终止条件:若判断当前节点为叶子节点,则将其值存入res中并返回res。
解题代码如下:
class Solution{
public:
vector<string> binaryTreePaths(TreeNode* root){
vector<string> res;
if(root == NULL) return res;
if(root->left == NULL && root->right == NULL) {res.push_back(to_string(root->val)); return res;}
vector<string> leftpath = binaryTreePaths(root->left);
for (int i = 0; i < leftpath.size(); i++) res.push_back(to_string(root->val) + "->" + leftpath[i]);
vector<string> rightpath = binaryTreePaths(root->right);
for (int i = 0; i < rightpath.size(); i++) res.push_back(to_string(root->val) + "->" + rightpath[i]);
return res;
}
};
提交后的结果如下:
方法二(对方法一优化)
其实可以不用额外创建一个res,另外还可以优化部分代码,使得整个程序变得更简洁明了。
class Solution{
public:
vector<string> binaryTreePaths(TreeNode* root){
if(root == NULL) return {};
if(root->left == NULL && root->right == NULL) return {to_string(root->val)};
vector<string> leftpath = binaryTreePaths(root->left);
vector<string> rightpath = binaryTreePaths(root->right);
leftpath.insert(leftpath.end(), rightpath.begin(), rightpath.end());
for (auto &temp : leftpath){
temp = to_string(root->val) + "->" + temp;
}
return leftpath;
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。