2叉樹遍歷的遞迴實現 使用c 模板

2021-07-09 08:46:23 字數 2408 閱讀 7381

2叉樹的遍歷, 為了效率, 不能用模板實現.

先用遞迴實現乙個, 找找感覺.

/// @file exam_x_x.cpp

/// @brief 用遞迴實現2叉樹遍歷

#include #include #include "mytree.h"

using namespace std;

void clear_cin();

void fntesttree();

int main(int argc, char** argv, char** envp)

void fntesttree()

// a+b*(c-d)/(e-f)-g

void clear_cin()

// mytree.h: inte***ce for the cmytree class.

////

#if !defined(afx_mytree_h__4898d3e6_65b2_4a17_9ca5_910bef38e313__included_)

#define afx_mytree_h__4898d3e6_65b2_4a17_9ca5_910bef38e313__included_

#if _msc_ver > 1000

#pragma once

#endif // _msc_ver > 1000

#define node_left true

#define node_right false

templateclass cmytreenode

~cmytreenode() {}

t m_element; ///< 元素

cmytreenode* m_pparent; ///< 父節點

cmytreenode* m_pchildleft; ///< 左孩子結點

cmytreenode* m_pchildright; ///< 右孩子結點

};templateclass cmytree

virtual ~cmytree()

cmytreenode* insertrootnode(t element);

cmytreenode* makenewnode(t element);

cmytreenode* insertnode(cmytreenode* pnode, bool isleft, t element);

cmytreenode* insertnode(cmytreenode* pnode, bool isleft, cmytreenode* pnodechildexist);

cmytreenode* getrootnode()

void printtree_dlr(cmytreenode* ptreenode); ///< 前序-遍歷列印

void printtree_ldr(cmytreenode* ptreenode); ///< 中序-遍歷列印

void printtree_lrd(cmytreenode* ptreenode); ///< 後序-遍歷列印

void free(cmytreenode* ptreenode); ///< 釋放資源

private:

cmytreenode* m_proot;

};templatevoid cmytree::free(cmytreenode* ptreenode)

}templatevoid cmytree::printtree_dlr(cmytreenode* ptreenode)

}templatevoid cmytree::printtree_ldr(cmytreenode* ptreenode)

}templatevoid cmytree::printtree_lrd(cmytreenode* ptreenode)

}templatecmytreenode* cmytree::insertrootnode(t element)

return m_proot;

}templatecmytreenode* cmytree::makenewnode(t element)

templatecmytreenode* cmytree::insertnode(cmytreenode* pnode, bool isleft, t element)

return pnode;

}templatecmytreenode* cmytree::insertnode(cmytreenode* pnode, bool isleft, cmytreenode* pnodechildexist)

return pnodechildexist;

}#endif // !defined(afx_mytree_h__4898d3e6_65b2_4a17_9ca5_910bef38e313__included_)

二叉樹非遞迴遍歷c 實現

三種遍歷演算法均採用棧來實現 1.前序遍歷 先訪問根節點,再訪問左子樹,最後訪問右子樹 先將根節點進棧,棧不空時迴圈 2.中序遍歷演算法 左中右 從根節點開始,將所有左節點一一進棧,當無左節點時表示棧頂節點無左子樹,然後出棧這個節點,並訪問它,將tmp指向剛出棧節點的右孩子節點,對右子樹進行同樣的處...

演算法 C 實現二叉樹遍歷(遞迴 非遞迴)

完成二叉樹建立,然後分別採用前序中序後序三種方式輸出結果。include include include 節點結構體 struct node 構建二叉樹 void inertnode node node,int value else else else 前序遍歷遞迴實現 void preorder ...

二叉樹的非遞迴遍歷C 實現

include include define maxsize 100 using namespace std typedef struct btnode bitnode void createtree btnode root root val c createtree root lchild cre...