力扣-二叉树-257 二叉树的所有路径

思路

除去根节点,每一层添加->val,然后使用前序遍历的顺序

代码

cpp 复制代码
class Solution {
public:
    vector<string> res;
    void getTreePaths(string s, TreeNode* root){
        s += "->";
        s += to_string(root->val);
        if(root->left == nullptr && root->right == nullptr){
             res.push_back(s);
             return;
        }
        
        if(root->left) getTreePaths(s, root->left);
        if(root->right) getTreePaths(s, root->right);

    }

    vector<string> binaryTreePaths(TreeNode* root) {
        if(root->left == nullptr && root->right == nullptr){
            res.push_back(to_string(root->val));
            return res;
        }
        string s;
        if(root->left) getTreePaths(to_string(root->val), root->left);
        if(root->right) getTreePaths(to_string(root->val), root->right);

        return res;
    }
};
相关推荐
嗜好ya2 分钟前
LeetCode 560: 和为K的子数组
数据结构·算法·leetcode
络717 分钟前
HashMap的put、get方法详解(附源码)
算法·哈希算法·hashmap
微光-沫年31 分钟前
141-CEEMDAN-VMD-Transformer-BiLSTM-ABKDE多变量区间预测模型!
算法·matlab·回归
闪电麦坤951 小时前
数据结构:数组:合并数组(Merging Arrays)
数据结构·算法
myloveasuka2 小时前
leetcode11.盛最多水的容器
c语言·数据结构·c++·leetcode
C++ 老炮儿的技术栈2 小时前
tinyxml2 开源库与 VS2010 结合使用
c语言·数据结构·c++·算法·机器人
平平无奇我要摘星星2 小时前
leetcode1_455.分发饼干
算法·leetcode
Joern-Lee2 小时前
机器学习算法:支持向量机SVM
算法·机器学习·支持向量机
秋说3 小时前
【PTA数据结构 | C语言版】计算1~n与1~m每一项相互乘积的和
c语言·数据结构·算法
秋说3 小时前
【PTA数据结构 | C语言版】计算1~n平方的和加上1~n的和
c语言·数据结构·算法