现在的位置: 首页 > 综合 > 正文

CareerCup-4.8

2013年09月02日 ⁄ 综合 ⁄ 共 1070字 ⁄ 字号 评论关闭

You are given a binary tree in which each node contains a value Design an algorithm 
to print all paths which sum up to that value Note that it can be any path in the tree 
- it does not have to start at the root 

#include <iostream>
#include <vector> 
using namespace std;  
typedef int Data;  

struct Node  
{  
    Node(Data d):data(d){left = right = NULL;};  
    Data data;  
    Node* left;  
    Node* right;
    Node* parent; 
};
  
class Tree  
{  
public:  
    Tree():root(NULL){};  
    Node* root;
    void findPath(int sum)
    {
        vector<Data> vector;
        findPath(root, vector, sum);
    };
private:
    void findPath(Node* head, vector<Data> vector, int sum)
    {
        if(head == NULL) return;
        vector.push_back(head->data);
        int temp = 0;
        for(int i=vector.size()-1; i>-1; i--)
        {
            temp += vector.at(i);
            if(temp == sum)
            {
                cout<<"Find: ";
                for(int j=vector.size()-1; j>=i; j--)
                {
                    cout<<vector.at(j)<<" ";
                }
                cout<<endl;
            }
        };
        if(head->left != NULL)
        {
            findPath(head->left, vector, sum);
            vector.pop_back();
        }
        if(head->right != NULL)
        {
            findPath(head->right, vector, sum);
            vector.pop_back();
        }
    };
};

int main()  
{  
    Tree tree;
    tree.root = new Node(5);
    tree.root->left = new Node(1);
    tree.root->right = new Node(7);
    tree.root->left->right = new Node(4);
    tree.root->left->right->left = new Node(3);
    tree.findPath(7);
    system("pause");  
};

抱歉!评论已关闭.