二叉樹基本操作及面試題

2021-07-31 17:33:55 字數 2513 閱讀 1622

#include#include#include#includeusing namespace std;

templatestruct binarytreenode//給出二叉樹節點的結構體

t _value;//值

binarytreenode* _pleft;//左孩子

binarytreenode* _pright;//右孩子

};templateclass binarytree

binarytree(const t arr, size_t size, const t& invalid)//建構函式

binarytree(const binarytree& bt)//拷貝構造

binarytree& operator=(const binarytree& bt)

return *this;

} ~binarytree()

void preorder_nor()//先序遍歷 非遞迴 }

void inorder_nor()//中序遍歷 非遞迴

pcur = s.top(); //取棧頂

cout<_value<<" "; //訪問

s.pop();//出棧

//方法1 右子樹不存在 單獨處理

while(null == pcur->_pright && !s.empty())//處理左單支樹可以一次性連續處理 注意條件應加上棧不為空,否則最上面節點右子樹為空 但進來後棧為空

pcur = pcur->_pright;//右子樹存在

//方法2 直接處理右子樹

//pcur = pcur->_pright;

} coutnode* pcur = _proot;

node* prev = null;//臨時變數 儲存剛剛訪問過的節點

while(pcur || !s.empty())

if(!s.empty())//???????

else

pcur = pcur->_pright;

} } }

bool iscompletebinarytree()

else

else if(pcur->_pleft)

else if(pcur->_pright)

return false;

else

flag = true;

}q.pop();

}return true;

}void preorder()

node* parent(node* pnode)//

node* _proot;

node* getleftchild(node* pcur)//左孩子

node* getrightchild(node* pcur)//右孩子

size_t _height(node* proot)//求樹高

size_t getleefcount(node* proot)//葉子節點個數

size_t getklevelcount(node* proot, size_t k)//獲取第k層節點個數

void binarymirror_nor(node* proot)//求映象 非遞迴

} //遞迴 求二叉樹映象 先序

void binarymirror(node* proot) }

private:

void _createbinarytree(node* &proot, const t arr, size_t size, size_t &idex, const t& invalid)//建立 }

node* _copybinarytree(node* proot)//拷貝

return pnewroot;

} void _destorybinarytree(node*& proot)//銷毀 }

void _preorder(node* proot) }

void _inorder(node* proot) }

void _postorder(node* proot) }

void _levelorder(node* proot) }

node* _parent(node* proot, node* pcur)//獲取某節點的雙親

};#include"test.h"

void funtest(){

char* arr = "124##5##36##7";

char* arr1 = "124##5##3";

size_t size = strlen(arr);

binarytreebt(arr, size, '#');

binarytreebt1(bt);

binarytreebt2(arr1, strlen(arr1), '#');

bt2 = bt;

//cout<_value//binarytreenode* pnode = bt.getleftchild(bt._proot->_pright);

//cout<_value<

二叉樹的基本操作及部分面試題

1.構造二叉樹 include include include include using namespace std template struct binarytreenode template class binarytree binarytree const t array,size t s...

資料結構 二叉樹基本操作 二叉樹面試題

二叉樹的基本概念就不多說了 如下 binarytree.c pragma once include include include include typedef char btdatatype typedef struct binarytreenode btnode a是乙個前序遍歷的陣列 二叉樹...

二叉樹的基本操作與面試題

面試題 拷貝二叉樹 前序遍歷非遞迴 二叉樹的映象遞迴 二叉樹的映象非遞迴 求二叉樹中結點的個數 獲取二叉樹中葉子結點的個數 求二叉樹中k層結點的個數 求二叉樹的高度 其中用到的佇列 棧的基本操作 二叉樹的基本操作 queue.h pragma once typedef char btdatatype...