// 微软100题之一二叉查找树变双向链表.cpp : 定义控制台应用程序的入口点。
//微软100题之四 二叉查找树找出和为某一值的所有路径
#include "stdafx.h"
#include <iostream>
#include <stack>
#define N 100
int path[N]={0};// used for calculating the path
using namespace std;
struct BSTreeNode
{
int m_nValue;
BSTreeNode *m_pLeft;
BSTreeNode *m_pRight;
};
void buildBSTree(BSTreeNode *&root, int value)
{
if(root==NULL)
{
root = new BSTreeNode();
root->m_nValue = value;
root->m_pLeft = NULL;
root->m_pRight = NULL;
}
else
if(root->m_nValue>value)
{
buildBSTree(root->m_pLeft,value);
}
else
if(root->m_nValue<value)// insert into rightchild
{
buildBSTree(root->m_pRight,value);
}
else ;//when exist same element skip
}
void midprint(BSTreeNode *root)//要传递指针的引用才好使。 unreverse mid 每一个元素都要入栈,出战的顺序即是遍历的顺序
{
stack<BSTreeNode*> stk;
BSTreeNode *p=root;
while(p!=NULL||stk.empty()==0)
{
while(p!=NULL)
{
stk.push(p);
p=p->m_pLeft;
}
if(stk.empty()==0)
{
p=stk.top();
cout<<p->m_nValue<<" ";//all the element should be push into the stack then pop
stk.pop();
p=p->m_pRight;
}
}
}
BSTreeNode *treeToList(BSTreeNode *root)// 在中序非递归遍历时处理每个元素。每一个元素都要入栈,出战的顺序即是遍历的顺序
{
stack<BSTreeNode*> stk;
BSTreeNode *p=root,*q=NULL,*t,*head;//q initialized as NULL
while(p!=NULL||stk.empty()==0)
{
while(p!=NULL)
{
stk.push(p);
p=p->m_pLeft;
}
if(stk.empty()==0)
{
p=stk.top();
//cout<<p->m_nValue<<" ";//all the element should be push into the stack then pop
t=p;
p=t->m_pRight;// p serve the searching record in the tree
if(q==NULL)
{
q=t;head=q;
q->m_pRight=NULL;
q->m_pLeft=q;// the leftchild of the head refers to itself
}
else
{
t->m_pRight = q->m_pRight;
q->m_pRight = t;
t->m_pLeft = q;
q = t;
}
stk.pop();
}
}
return head;
}
void searchList(BSTreeNode *root)
{
BSTreeNode *p=root;
while(p!=NULL)
{
cout<<p->m_nValue<<" ";
p=p->m_pRight;
}
}
void calculatePath(BSTreeNode *root,int remain,int i)// i represent the layer
{
if(root->m_nValue==remain)// find a path, from 0 layer to i layer
{
path[i]=remain;
for(int k=0;k<=i;k++)
cout<<path[k]<<" ";
cout<<endl;
}
else if(root->m_nValue>remain)
return ;
else
{
if(root->m_pLeft!=NULL||root->m_pRight!=NULL)
{
path[i]=root->m_nValue;
if(root->m_pLeft!=NULL)
calculatePath(root->m_pLeft,remain-root->m_nValue,i+1);
if(root->m_pRight!=NULL)
calculatePath(root->m_pRight,remain-root->m_nValue,i+1);
}
else
return ;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
BSTreeNode *root=NULL,*head;
int n,m;
cout<<" input n "<<endl;
cin>>n;
cout<<" input values "<<endl;
int *value = new int[n];
for(int i=0; i<n; i++)
{
cin >> value[i];
}
for (int i = 0; i < n; i++)
{
buildBSTree(root, value[i]);
}
cout<<" search tree "<<endl;
midprint(root);
cout<<endl<<"find the path which sum is m, please input m "<<endl;
cin>>m;
calculatePath(root,m,0);
cout<<endl<<" search list "<<endl;
head = treeToList(root);
searchList(head);
system("pause");
return 0;
}
微软面试100题之一,之四 二叉查找树变双向链表 和为某一值的所有路径
最新推荐文章于 2017-09-02 10:57:21 发布