您的位置:首页 > 其它

笔试题:求二叉树和值为sum的所有路径

2015-09-06 17:00 399 查看
#include <iostream>
#include <stack>
using namespace std;

struct  TreeNode
{
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int d = int()):data(d), left(NULL), right(NULL){}
};
class Tree
{
public:
Tree() :root(NULL){}
void Insert(int VLR[], int LVR[],int n)
{
Insert(root, VLR, LVR, n);
}
void Printf()
{
Printf(root);
}
void PrintfSum(int sum)
{
stack<TreeNode*> st;
PrintfSum(root, st,sum);
}
private:
void PrintfSum(TreeNode* t, stack<TreeNode*>& st,int sum)
{
if (t == NULL)
{
if (sum == 0)
{
stack<TreeNode *> sp = st;
while (sp.empty() == false)
{
cout << sp.top()->data << " ";
sp.pop();
}
cout << endl;
}
//st.pop();
return;
}
else
{
st.push(t);
sum -= t->data;
PrintfSum(t->left, st,sum);
if (t->right!=NULL)
PrintfSum(t->right, st,sum);
st.pop();
}
}
void Insert(TreeNode *&t, int VLR[], int LVR[], int n)
{
if (n == 0)return;
int i = 0;
while (VLR[0] != LVR[i])i++;
t = new TreeNode(VLR[0]);
Insert(t->left, VLR + 1, LVR, i);
Insert(t->right, VLR + i + 1, LVR + i+1, n - i - 1);
}
void Printf(TreeNode *t)
{
if (t != NULL)
{
cout << t->data << " ";
Printf(t->left);
Printf(t->right);
}
}
private:
TreeNode *root;
};
int main()
{
Tree t;
int VLR[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int LVR[] = {4,3,6,5,7,2,9,8,10,1,12,11,13,14,15,16};
t.Insert(VLR,LVR,sizeof(LVR)/sizeof(int));
t.Printf();
cout << endl;
t.PrintfSum(24);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: