算法与数据结构基础4:C++二叉树实现及遍历方法大全(二)

2015-01-27 05:55:41 · 作者: · 浏览: 15
********************************************************************* void BSTree::Insert(int x) { Node* tmp = new Node(x); if (!m_root){ m_root = tmp; } else{ Node* pre = m_root; Node* cur = m_root; while (cur){ pre = cur; cur = (x < cur->data) ? (cur->lchild) : (cur->rchild); } (x < pre->data) ? (pre->lchild = tmp) : (pre->rchild = tmp); } } unsigned short BSTree::Size() { return CountSize(m_root); } unsigned short BSTree::Deep() { return CountDeep(m_root); } unsigned short BSTree::Leaf() { return CountLeaf(m_root); } bool BSTree::IsEmpty() { return m_root == NULL; } void BSTree::PreorderTraversal() { PreorderTraversal(m_root); cout << endl; } void BSTree::InorderTraversal() { InorderTraversal(m_root); cout << endl; } void BSTree::PostorderTraversal() { PostorderTraversal(m_root); cout << endl; } void BSTree::DepthFirstSearch() { DepthFirstSearch(m_root); cout << endl; } void BSTree::BreadthFirstSearch() { BreadthFirstSearch(m_root); cout << endl; }
// mian.cpp

// test for BSTree
#include "BSTree.h"
#include 
  
   
#include 
   
     using namespace std; int main() { BSTree tree; int arr[6] = {5, 4, 8, 1, 7, 10}; for (int i = 0; i < 6; ++i){ tree.Insert(arr[i]); } tree.PreorderTraversal(); tree.InorderTraversal(); tree.PostorderTraversal(); tree.DepthFirstSearch(); tree.BreadthFirstSearch(); cout << "size:" << tree.Size() << endl; cout << "deep:" << tree.Deep() << endl; cout << "leaf:" << tree.Leaf() << endl; system("pause"); return 0; }
   
  


// 输出截图