【2】在二叉樹中找出和爲某一值的全部路徑

/*******************************************************************node

 100-4.題目:在二元樹中找出和爲某一值的全部路徑ios

輸入一個整數和一棵二元樹。從樹的根結點開始往下訪問一直到葉結點所通過的全部結點造成一條路徑。 打印出和與輸入整數相等的全部路徑。例如輸入整數22 和二元樹則打印出兩條路徑:10, 12 和10, 5, 7。spa

\*******************************************************************指針

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

typedef struct BTreeNode{
    int data;
	BTreeNode *left;
	BTreeNode *right;
}BTreeNode,*BTree;

void add_btreenode(BTreeNode *&a_tree,int value){
    if(a_tree == NULL){
        a_tree = new BTreeNode();
        a_tree->data = value;
        a_tree->left = NULL;
        a_tree->right = NULL;
        cout<<a_tree->data<<endl;
    }else if(value < a_tree->data){
        add_btreenode(a_tree->left,value);
    }else if(value > a_tree->data){
        add_btreenode(a_tree->right,value);
    }

}
void preorder_btree(BTreeNode *a_tree,vector<int> v,int sum,int given){
    if(a_tree != NULL){
        sum += a_tree->data;
        v.push_back(a_tree->data);
        cout<<"sum:"<<sum<<':'<<a_tree->data<<' ';
        if(a_tree->right == NULL && a_tree->left == NULL){
            if(sum == given){
                for (vector<int>::iterator iter=v.begin();iter!=v.end();iter++){
                    cout<<*iter<<" ";
                    
                }
                cout<<endl;
            }
        }
        cout<<"l";
        preorder_btree(a_tree->left,v,sum,given);
        cout<<"r";
        preorder_btree(a_tree->right,v,sum,given);
        v.pop_back();
        sum -= a_tree->data;
    }
    
}
int main(){
    int a[] ={4,3,5,2,9};
    BTreeNode *a_tree=NULL;
    for(int i=0;i<5;i++){
        cout<<a[i]<<':';
        add_btreenode(a_tree,a[i]);
        
    }
    cout<<"######"<<endl;
    
    vector<int> v;
    int given=9;
    int sum=0;
    preorder_btree(a_tree,v,sum,given);
    
    return 0;
}

 

指針:code

指針是一個變量,其值爲另外一個變量的地址,即,內存位置的直接地址。內存

#include <iostream>
using namespace std;

int main(){
	int *p;
	int a = 10;
	p = &a;
    
	cout<<"a:"<<a<<endl;   //a:10
	cout<<"p:"<<p<<endl;   //p:0x7fff5b42fb2c
	cout<<"*p:"<<*p<<endl; //*p:10
    return 0;
}
相關文章
相關標籤/搜索