二叉树
一、题目:(感谢 http://blog.csdn.net/v_JULY_v 提供的题目)
在二元树中找出和为某一值的所有路径
输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。例如:输入整数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
};
二、分析:
1.遍历该二叉树由树根至树叶的每一条路径
2.把每条路径的数值累加,与输入整数对比
3.输出符合要求的路径
三、设计知识:
1.二叉树的构造(通过键盘键入二叉树的前序序列构造二叉树)
2.遍历二叉树的每条路径
四、代码:
#include<iostream> using namespace std; const int stackSize = 10; int total = 0; 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 }; class BinaryTree { public : BinaryTree(); ~BinaryTree(); BinaryTreeNode* Getroot(); void InOrder(BinaryTreeNode *root);//中序遍历树 void doMain(BinaryTreeNode *root);//遍历树的所有路径 private : BinaryTreeNode *root; BinaryTreeNode *Create(); void Release(BinaryTreeNode *root); int stackArray[stackSize];//树值栈 int size;//栈大小 void push(int x,BinaryTreeNode *root); void pop(); int stackSum();//栈中值总和 void printStack();//打印栈的值 }; BinaryTree::BinaryTree() { this->root = Create(); size = -1; } BinaryTree::~BinaryTree() { Release(this->root); } BinaryTreeNode *BinaryTree::Getroot() { return this->root; } BinaryTreeNode *BinaryTree::Create() { BinaryTreeNode *root; int ch; cout<<"请输入节点数据:"<<endl; cin>>ch; if(ch==0) root = NULL; else{ root = new BinaryTreeNode; root->m_nValue = ch; root->m_pLeft = Create(); root->m_pRight = Create(); } return root; } void BinaryTree::InOrder(BinaryTreeNode *root) { if (root==NULL) return; //递归调用的结束条件 else{ InOrder(root->m_pLeft); //中序递归遍历root的左子树 cout<<root->m_nValue<<" "; //访问根结点的数据域 InOrder(root->m_pRight); //中序递归遍历root的右子树 } } void BinaryTree::Release(BinaryTreeNode *root) { if (root != NULL){ Release(root->m_pLeft); //释放左子树 Release(root->m_pRight); //释放右子树 delete root; } } void BinaryTree::push(int x,BinaryTreeNode *root) { if(size == stackSize - 1) throw "上溢出"; else{ size++; stackArray[size] = x; } } void BinaryTree::pop() { if(size == -1) throw "下溢出"; else{size--;} } void BinaryTree::doMain(BinaryTreeNode *root) { if(root != NULL) push(root->m_nValue,root); else return; if(root->m_pLeft == NULL && root->m_pRight == NULL) { if(total == stackSum()) printStack(); pop(); }else{ doMain(root->m_pLeft); doMain(root->m_pRight); pop(); } } int BinaryTree::stackSum() { int sum = 0; for(int i=0;i<=size;i++) { sum+=stackArray[i]; } return sum; } void BinaryTree::printStack() { for(int i=0;i<=size;i++) { cout<<stackArray[i]<<" "; } cout<<endl; } void main() { BinaryTree bt; BinaryTreeNode* root = bt.Getroot(); bt.InOrder(root);//中序遍历树 cout<<endl; int ch; cout<<"请输入一整数:"; cin>>ch; total = ch; bt.doMain(root);//遍历树的每条路径 }
五、测试:
1.原题目测试数据:
2.自己编写测试数据:
**输入数据格式为:
(测试1)10 ENTER 5 ENTER 4 ENTER 0 ENTER 0 ENTER 7 ENTER 0 ENTER 0 ENTER 12 ENTER 0 ENTER 0 ENTER
(测试2)略