Binary Tree Paths

本文介绍了一种通过先序遍历的方式,找到给定二叉树中所有从根节点到叶子节点的路径的方法。具体实现包括深度优先搜索(DFS),并使用字符串流(stringstream)来构建路径字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["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> path;
        vector<string> finalResult;
        deepTravel(root,path,finalResult);
        return finalResult;
    }
    
    void deepTravel(TreeNode* root,vector<string>& tempPaths,vector<string>& finalResult)
    {
        //判断当前结点是否为空
        if(root == NULL)
            return;
        //当前结点不为空就把当前结点的值转换为字符串。然后压入路径vector中
        string temp;
        stringstream ss;
        ss<<root->val;
        ss>>temp;
        if(tempPaths.size()!=0)//如果前面已经有结点了,就添加箭头。
            tempPaths.push_back("->");
        tempPaths.push_back(temp);
        
        //如果当前结点没有左右子树,就将tempPath中的结点组合成一整个路径字符串。然后压入finalResult中
        if(root->left == NULL && root->right==NULL)
        {
            string temp;
            for(vector<string>::iterator iter = tempPaths.begin(); iter!=tempPaths.end();iter++)
            {
                temp+=*iter;
            }
            finalResult.push_back(temp);
            return;
        }
        //如果当前结点有左右子树,就递归下去遍历
        if(root->left != NULL)
        {
            deepTravel(root->left,tempPaths,finalResult);    
            //先把左子树的结果弹出
            tempPaths.pop_back();
            tempPaths.pop_back();
      
        }
          //如果当前结点有左右子树,就递归下去遍历
        if(root->right != NULL)
        {
            deepTravel(root->right,tempPaths,finalResult);
            tempPaths.pop_back();
            tempPaths.pop_back();
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值