1. 程式人生 > >劍指offer 24:二叉樹中和為某一值的路徑

劍指offer 24:二叉樹中和為某一值的路徑

二叉樹中和為某一值的路徑

#include <iostream>
#include <vector>
using namespace std;



using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    /*TreeNode(int x)
        : val(x), left(NULL), right(NULL)
    {

    }*/
};

class Solution
{
public:
    vector< vector<int> > m_res;

    vector< vector<int> > FindPath(TreeNode* root, int Number) {
        if (root == NULL) {
            return m_res;
        }

        vector<int> path;

        FindPath(root, Number, path, 0);

        return m_res;
    }

    void FindPath(TreeNode* root, int Number, vector<int> path, int CurrenSum) {
        CurrenSum += root->val;
        path.push_back(root->val);

        if (CurrenSum == Number && ((root->left == NULL && root->right == NULL))) {
            cout<< "find path" << endl;

            for (int i = 0; i < path.size(); i++) {
                cout << path[i] << " ";
            }
            cout << endl;
            m_res.push_back(path);
        }

        if(root->left != NULL) {
            FindPath(root->left, Number, path, CurrenSum);
        }

        if(root->right != NULL) {
            FindPath(root->right, Number, path, CurrenSum);
        }
     }
    //另外的方法
};

int main()
{

    TreeNode tree[5];

    tree[0].val = 10;
    tree[0].left = &tree[1];
    tree[0].right = &tree[2];

    tree[1].val = 5;
    tree[1].left = &tree[3];
    tree[1].right = &tree[4];

    tree[2].val = 12;
    tree[2].left = NULL;
    tree[2].right = NULL;

    tree[3].val = 4;
    tree[3].left = NULL;
    tree[3].right = NULL;


    tree[4].val = 7;
    tree[4].left = NULL;
    tree[4].right = NULL;

    Solution solu;
    vector< vector<int> > res = solu.FindPath(&tree[0], 19);

    for (int i = 0; i < res.size(); i++) {
        for (int j = 0;  j< res[i].size(); j++) {
            cout << res[i][j] << endl;
        }
        //cout << endl;
    }



    return 0;
}