257 Binary Tree Paths

本文介绍了一种使用深度优先搜索(DFS)算法来查找给定二叉树中所有从根节点到叶子节点路径的方法。通过递归方式遍历树结构,并记录路径,最终收集所有路径并返回。

题意:给定二叉树,找出所有根到叶子的路径

分析:dfs.

代码:

/**
 * 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> ans;
        //if(root==nullptr)  return ans;
        string curPath="";
        dfs(ans,curPath,root);
        return ans;
    }
    string getstring ( const int n ){
        std::stringstream newstr;
        newstr<<n;
        return newstr.str();
    }
    void dfs(vector<string> &paths,string curPath,TreeNode* root){
        if(root==nullptr)  return;
        if(root->left==nullptr&&root->right==nullptr){
            paths.push_back(curPath+getstring(root->val));
            return;
        }
        dfs(paths,curPath+getstring(root->val)+"->",root->left);
        dfs(paths,curPath+getstring(root->val)+"->",root->right);
    }
};


Binary Tree Paths with Sum Equal to a Certain Value Score: 30 Author: Zhu Yungang Institution: Jilin University Given a binary tree where the nodes are non-zero integers, given an integer K, write a program to find all paths starting from the root node and ending at leaf nodes where the sum of the node values ​​equals K. For example, if K=15, for the binary tree t shown below, there are 2 paths that satisfy the condition: 8-5-2 and 8-7. If no path satisfies the condition, it should still be recognized. img.jpg Input Format: The input consists of two lines. The first line contains a set of space-separated integers, not exceeding 100, representing the preorder sequence of the binary tree with null pointer information (represented by 0). The second line is an integer K. Output Format: The first line of the output is an integer representing the number of paths that satisfy the condition; if no path satisfies the condition, output 0. Starting from the second line, each line represents a path that meets the condition. If multiple paths meet the condition, output them sequentially from left to right. Each node value in the path is followed by a space. If two different paths contain exactly the same node values, both must be output. Input Example 1: 8 5 1 0 0 2 0 0 7 0 0 15 Output Example 1: 2 8 5 2 8 7 Input Example 2: -1 2 0 0 3 0 0 2 Output Example 2: 1 -1 3 Input Example 3: 1 1 0 0 1 0 0 2 Output Example 3: 2 1 1 1 1 Input Example 4: -1 2 0 0 3 0 0 8 Output Example 4: 0C++
最新发布
11-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值