zoukankan      html  css  js  c++  java
  • 输出二叉树中路径上结点值之和为给定值的所有路径

    #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;
    }

    /*

    */

  • 相关阅读:
    Mybatis的动态sql以及分页
    Mybatis入门
    使用java代码操作Redis
    Redis安装和基本操作
    idea安装以及使用
    卢卡斯定理 Lucas (p为素数)
    三分/优选法(黄金分割法)求单峰函数极值
    缩点tarjan
    tarjan 求割点
    tarjan
  • 原文地址:https://www.cnblogs.com/wuxiangli/p/5661527.html
Copyright © 2011-2022 走看看