ACM做題心得(1)
阿新 • • 發佈:2019-01-23
left
資料結構裡最熟悉的就是樹這一部分,雖然很久沒有敲過了,但還是比較有親切感~
借用了以前的程式碼,改動了一些,可以執行出結果,奇怪的是總是出現了Memory Limit Exceed(程式執行時超過題目允許的最大記憶體),多次改動後仍沒有解決問題……哪位仁兄有空可以幫忙看一下哈~~不勝感激!
以下是偶的程式碼:
//判斷某結點是左孩子還是右孩子
#include<iostream>
using namespace std;
struct BiNode
{
char data;
BiNode *lchild,*rchild;
};
class BiTree
{
public:
//BiTree(){root=NULL;}
BiTree();
~BiTree(void);
BiNode *Getroot(); //獲得指向根結點的指標
int judge(BiNode *root,char x,BiNode *pre);
private:
BiNode *root; //指向根結點的頭指標
void Create(BiNode *&root);
void Release(BiNode *root);
};
int max(int x,int y)
{
return (x>y?x:y);
}
BiTree::BiTree()
{
Create(root);
this->root=root;
}
BiTree::~BiTree(void)
{
Release(root);
}
BiNode * BiTree::Getroot() //返回二叉樹的根結點
{
return root;
}
void BiTree::Create(BiNode *&root) //按先序遍歷生成一棵二叉樹
{
char ch;
cin>>ch;
if(ch=='#')root=NULL;
else
{
root=new BiNode; //生成一個結點
root->data=ch;
Create(root->lchild); //遞迴建立左子樹
Create(root->rchild); //遞迴建立右子樹
}
}
void BiTree::Release(BiNode *root) //釋放二叉樹佔用的空間
{
if(root!=NULL)
{
Release(root->lchild); //釋放左子樹
Release(root->lchild); //釋放左子樹
delete root;
}
}
int UnEmpty(int p1,int p2)
{
if(p1!=0)return p1;
else if(p2!=0)return p2;
else return 0;
}
int BiTree::judge(BiNode *root,char x,BiNode *pre)
{
if(root==NULL) return 0;
if(root->data==x)
{
if(pre==NULL) //前一個根結點為空
return 3;
if(pre->lchild==root) //前一個結點的左孩子為root
return 1;
else return 2; //右孩子
}
else
{
pre=root;
return UnEmpty(judge(root->lchild,x,pre),judge(root->rchild,x,pre));
}
}
int main()
{
BiTree tree;
char x;
cin>>x;
BiNode *pre = NULL;
int y=tree.judge(tree.Getroot(),x,pre);
if(y==0)
cout<<"none"<<endl;
else if(y==1)
cout<<"left"<<endl;
else if(y==2)
cout<<"right"<<endl;
else cout<<"root"<<endl;
return 0;
}