257. Binary Tree Paths(树型题)

problem:

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

tip:

二叉树返回所有根到叶结点的路径,树型题目,多用递归。

solution:

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        if(!root) return {};
        if(!root->left && !root->right) return {to_string(root->val)};
        vector<string> res;
        for(string st : binaryTreePaths(root->left))
        {
            res.push_back(to_string(root->val)+"->"+st);//???
        }
        for(string st : binaryTreePaths(root->right))
        {
            res.push_back(to_string(root->val)+"->"+st);
        }
        return res;
    }
};

2.当前路径结束后,将它存储。

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
       if(!root) return {};
       vector<string> res;
        if(root) helper(root,"",res);
        return res;
    }
    //这里的out代表当前结点之前的路径,当完成一条路径遍历后,将其存储在vector中
    void helper(TreeNode* root,string out,vector<string>& res)//这里的引用很重要,没有的话程序是错误的.因为不加引用只是对形参做了修改,实参没有变化。
    {
        if(!root->left && !root->right) res.push_back(out+to_string(root->val));
        if(root->left) helper(root->left,out+to_string(root->val)+"->",res);
        if(root->right) helper(root->right,out+to_string(root->val)+"->",res)
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值