• 输出二叉树中路径上结点值之和为给定值的所有路径


    #include<iostream>
    #include<vector>
    #include<algorithm>
    #include<stdint.h>
    using namespace std;
    #include<list>
    #include<map>
    #include<queue>
    struct node
    {
    int val;
    node* left, *right;
    node(int _val) :val(_val), left(NULL), right(NULL){}
    };

    void findSum(node* head, int sum, vector<int>& paths, int level)
    {
    if (head == NULL) return;
    int tmp = sum;
    paths.push_back(head->val);

    for (int i = level; i >= 0; i--)
    {
    tmp -= paths[i];
    if (tmp == 0)
    {
    for (int j = i; j <= level; j++)
    cout << paths[j] << " ";
    cout << endl;
    }
    }

    findSum(head->left, sum, paths, level + 1);
    findSum(head->right, sum, paths, level + 1);
    paths.pop_back();

    }

    int main()
    {
    node n1(2), n2(3), n3(2), n4(-4), n5(3), n6(6), n7(1), n8(3), n9(1), n10(2);
    n1.left = &n2;
    n1.right = &n3;
    n2.left = &n4;
    n2.right = &n5;
    n3.left = &n6;
    n3.right = &n7;
    n4.left = &n8;
    n8.left = &n9;
    n9.left = &n10;
    vector<int> paths;
    findSum(&n1, 5, paths, 0);
    return 0;
    }

    /*

    */

  • 相关阅读:
    帮助智力障碍的可怜儿童
    PE556
    ZJOIDay2T1 BB题解
    CTSC2016游记
    再次被老爸钦点退役
    欧拉筛
    考据
    51nod 1020 逆序排列(动态规划)
    51nod 1186 质数检测(Miller-Rabin算法)
    大整数类模板
  • 原文地址:https://www.cnblogs.com/wuxiangli/p/5661527.html
Copyright © 2020-2023  润新知