自己寫備忘的,還差,後續建立二叉樹,後續非遞迴,線索化,二叉樹最長路徑,二叉樹最遠2個節點之間的距離沒寫。
記住一定要加
#include "stdafx.h" #include<iostream>#include<queue> #include<stack>using namespace std;typedef struct node{ int data; struct node *left; struct node *right;}Node,*Bitree;Bitree createTree()//前序建立二叉樹{ int ch; Bitree t; cin>>ch; if(ch == 0) return NULL; else{ t = (Bitree)malloc(sizeof(Node)); t->data = ch; t->left = createTree(); t->right = createTree(); return t; } }void preRecur(Bitree T)//前序遞迴遍曆二叉樹{ if(T != NULL) {cout<<T->data<<" "; preRecur(T->left); preRecur(T->right); }}void inRecur(Bitree T)//中續遞迴遍曆二叉樹{ if(T!=NULL) { inRecur(T->left); cout<<T->data<<" "; inRecur(T->right); } }void inNonRecur(Bitree T)//中序非遞迴遍曆二叉樹{ stack<Bitree> ss; Bitree p = T; while(p!=NULL || !ss.empty()) { while(p!=NULL) { ss.push(p); p = p->left; } if(!ss.empty()) { p = ss.top(); ss.pop(); cout<<p->data<<" "; p = p->right; } }}void preNonRecur(Bitree T)//前序非遞迴遍曆二叉樹{ if(T == NULL) return ; stack<Bitree> ss; Bitree p = T; while(p!=NULL || !ss.empty()) { while(p!=NULL) { cout<<p->data<<" "; ss.push(p); p = p->left; } if(!ss.empty()) { p = ss.top(); ss.pop(); p = p->right; } }}void layer(Bitree T)//層序遍曆二叉樹{ if(T==NULL) return; queue<Bitree> qu; qu.push(T); while(!qu.empty()) { Bitree r = qu.front(); cout<<r->data<<" "; qu.pop(); if(r->left!=NULL) qu.push(r->left); if(r->right!=NULL) qu.push(r->right); }} int depth(Bitree T)//二叉樹深度{ if(T==NULL) return 0; int n = depth(T->left); int m = depth(T->right); return m>n?(m+1):(n+1);}int width(Bitree T)//二叉樹寬度 { int max = 0; if(T == NULL) return max; queue<Bitree> Q; Q.push(T); int preCount = 0; int curCount = 1; max = 1; while(!Q.empty()) { preCount = curCount; curCount = 0; while(preCount>0) { Bitree b = Q.front(); cout<<b->data<<"\t"; Q.pop(); preCount--; if(b->left!=NULL) { Q.push(b->left); curCount++; } if(b->right!=NULL) { Q.push(b->right); curCount++; } } max = curCount>max?curCount:max; } return max; }int main(){cout<<"Build First Tree: "; Bitree root = createTree(); layer(root); cout<<endl; //cout<<"depth = "<<depth(root);inNonRecur(root);cout<<endl;//layer(root);//cout<<endl<<"width = "<<width(root)<<endl; getchar(); getchar(); return 0;}