二叉树构造与遍历

#include<iostream>
#include<stack>
#include<queue>
using namespace std;
/*class link{
public:
  int data;
  link* next;
  link(int d):data(d),next(NULL){}
  link *head;
  link* tail;
  
};
class stack{
public:
  link *top;
  int size;
  
  stack(int sz):top(NULL),size(sz){}
  stack():top(NULL),size(0){}
  ~stack(){
    clear();
  }
  void clear(){
    while(top!=NULL){
      link * temp = top;
      delete temp;
      top = top->next;
    }
    size = 0;
  }
  void push(int it){
    if(top==NULL){
      top = new link(it);
      size++;
    }else{
      link * temp = new link(it); //把新加入的值放进temp中
      temp->next = top; //让TEMP指向top,和stack连起来
      top = temp;  //此时的temp变成了top
    }
   
    
  }
  bool empty(){
    if(top==NULL)
      return true;
    else
      return false;
  }
  void pop(){
    link *temp = top;
    delete  temp;
    top = top->next;
    size--;
  }
};
*/

class BinTree{
public:
  int data;
  BinTree* left;
  BinTree* right;
 
  BinTree(int d):data(d),left(NULL),right(NULL){}
  BinTree* root;
  BinTree():root(NULL){}
  
  BinTree* createBintree(){
    BinTree* T = new BinTree;
    char ch;
    cin>>ch;
    if(ch=='#'){
      T = NULL;
    }else{
      T->data = ch;  //初始化当前结点
      T->left = createBintree(); //递归构造左子树
      T->right = createBintree(); //递归构造右子树
    }
    return T;
  }
  
  void preorder(BinTree* T){
    if(T==NULL){
      return;
    }else{
      cout<<T->data;  //访问根节点
      T->preorder(T->left);
      T->preorder(T->right);
    }
  }
  
  //非递归的前序遍历
  void preorder2(BinTree* T){
    stack<BinTree*> s;
    BinTree* temp = T;
    while(temp||!s.empty()){
      cout<<temp->data<<" ";  //打印当前结点
      s.push(temp);    //当前结点入栈
      temp = temp->left;  //访问左子树
      while(temp==NULL&&!s.empty()){
        temp = s.top();   //栈内最后一个保存为当前结点
        s.pop();   //pop一个出来
        temp = temp->right; //访问右子树
      }
    }
    
  }
  
  void print(BinTree* T){
    //层次遍历
    queue<BinTree*> q; //用于移动
    BinTree* cur = T;
    q.push(cur); //头结点入队
    //队列为空时循环结束
    while(!q.empty()){
      //队列头元素出队
      cur = q.front();
      q.pop();
      cout<<cur->data;
      //左孩子不为空入队
      if(cur->left!=NULL){
        q.push(cur);
      }
      //右孩子不为空时入队
      if(cur->right!=NULL){
        q.push(cur);
      }
    }
  
  }
  
  int height(BinTree* T){
    if(T){
      //递归求左右子树高度
      int lheight = height(T->left);
      int rheight = height(T->right);
      //树的高度等于左右子树中高的那个+1(因为有root)
      int height = (lheight>rheight)?lheight:rheight;
      height++;
      return height;
    }
    return 0;
  }
  
  
  
  
  
  
  
  
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值