4.在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12和10, 5, 7。
二元树节点的数据结构定义为:
struct BinaryTreeNode // a node in the binary tree
{
int m_nValue; // value of node
BinaryTreeNode *m_pLeft; // left child of node
BinaryTreeNode *m_pRight; // right child of node
};
/*
* SearchOneValue.h
*
* Created on: 2011-3-29
* Author: zq
*/
#ifndef SEARCHONEVALUE_H_
#define SEARCHONEVALUE_H_
class SearchOneValue{
private:
int* PathArr;
int arrSize;
int index;
struct BinaryNode{
int element;
BinaryNode* left;
BinaryNode* right;
BinaryNode(const int& theElem,BinaryNode* lt,BinaryNode* rt):
element(theElem),left(lt),right(rt){}
};
void PrintOneValuePath(BinaryNode* rt,int OneValue,int *PathArr,int index);
public:
BinaryNode* root;
SearchOneValue(int size = 20,int ind = 0,BinaryNode* rt = NULL):
arrSize(size),index(ind),root(rt){
PathArr = new int[arrSize];
}
~SearchOneValue(){
delete []PathArr;
makeEmpty(root);
}
void insert(const int &x,BinaryNode* &rt);
void PrintPath(int OneValue);
void makeEmpty(BinaryNode* &rt);
};
#endif /* SEARCHONEVALUE_H_ */
/*
* SearchOneValue.cpp
*
* Created on: 2011-3-29
* Author: zq
*/
#include <iostream>
#include "SearchOneValue.h"
using namespace std;
void SearchOneValue::insert(const int &x,BinaryNode* &rt){
if(NULL == rt)
rt = new BinaryNode(x,NULL,NULL);
else if(x < rt->element)
insert(x,rt->left);
else if(x > rt->element)
insert(x,rt->right);
else
;
}
void SearchOneValue::PrintOneValuePath(BinaryNode* rt,int OneValue,int *PathArr,int index){
if(NULL == rt) return;
//当前节点是叶子节点
if(rt->left == NULL && rt->right == NULL){
if(OneValue == rt->element){
cout << "\nFind the Path:" << endl;
for(int i = 0;i < index;++i)
cout << PathArr[i] << " ";
cout << rt->element;
}
return;
}
int tmpIndex = index;
if(PathArr != NULL && index < arrSize){
PathArr[tmpIndex] = rt->element;
tmpIndex++;
}
int value = OneValue - rt->element;
if(value >= 0){
PrintOneValuePath(rt->left,value,PathArr,tmpIndex);
PrintOneValuePath(rt->right,value,PathArr,tmpIndex);
}
}
void SearchOneValue::PrintPath(int OneValue){
PrintOneValuePath(root,OneValue,PathArr,index);
}
void SearchOneValue::makeEmpty(BinaryNode* &rt){
if(NULL == rt) return;
makeEmpty(rt->left);
makeEmpty(rt->right);
delete rt;
rt = NULL;
}
int main(){
SearchOneValue SOV;
int data;
int choice;
while(true){
cout << "\n\n\n ---主界面---\n\n\n";
cout << " 1. 插入操作 2. 查询操作\n";
cout << " 0. 退出\n";
cout << " 请选择操作: ";
cin >> choice;
switch(choice){
case 0:
return 0;
case 1:
cout << "请输入要插入的元素: " ;
cin >> data;
SOV.insert(data,SOV.root);
break;
case 2:
cout << "请输入要查询的值: ";
cin >> data;
SOV.PrintPath(data);
break;
}
}
return 0;
}
浙公网安备 33010602011771号