二叉树是一种特殊的树结构:每个节点最多有两个子节点。
二叉树的性质:
(1)二叉树第i层的节点数目最多为 2{i-1} (i≥1)。
(2)深度为k的二叉树至多有2{k}-1个结点(k≥1)。
(3)包含n个结点的二叉树的高度至少为log2 (n+1)。
(4)在任意一棵二叉树中,若终端结点的个数为n0,度为2的结点数为n2,则n0=n2+1。
实现:
bitTree.h
1 #pragma once 2 3 #include <iostream> 4 5 struct tree 6 { 7 int data; 8 tree *liftChild, *rightChild; 9 }; 10 11 class bitTree 12 { 13 public: 14 bitTree(); 15 ~bitTree(); 16 17 void insertTree(int data); 18 19 //前序遍历 20 void preorder(tree *p); 21 //中序遍历 22 void interthem(tree *p); 23 //后序遍历 24 void postorder(tree *p); 25 26 //计算二叉树节点数 27 int count(tree *p); 28 //统计叶子节点数 29 int findLeafNum(tree *p); 30 31 //获取二叉树根节点 32 tree *getRoot(); 33 34 static int leafNum; 35 36 private: 37 tree *root; 38 };
bitTree.cpp
1 int bitTree::leafNum = 0; 2 3 bitTree::bitTree() 4 { 5 root = NULL; 6 } 7 8 9 bitTree::~bitTree() 10 { 11 } 12 13 void bitTree::insertTree(int data) 14 { 15 tree *newTree = new tree; 16 newTree->data = data; 17 newTree->liftChild = newTree->rightChild = NULL; 18 19 if (NULL == root) 20 root = newTree; 21 else 22 { 23 tree *backup = NULL; 24 tree *current = root; 25 while (current != NULL) 26 { 27 backup = current; 28 if (current->data > data) 29 current = current->liftChild; 30 else 31 current = current->rightChild; 32 } 33 if (backup->data > data) 34 backup->liftChild = newTree; 35 else 36 backup->rightChild = newTree; 37 } 38 } 39 40 void bitTree::preorder(tree * p) 41 { 42 if (p != NULL) 43 { 44 std::cout << p->data << " "; 45 preorder(p->liftChild); 46 preorder(p->rightChild); 47 } 48 } 49 50 void bitTree::interthem(tree * p) 51 { 52 if (p != NULL) 53 { 54 interthem(p->liftChild); 55 std::cout << p->data << " "; 56 interthem(p->rightChild); 57 } 58 } 59 60 void bitTree::postorder(tree * p) 61 { 62 if (p != NULL) 63 { 64 postorder(p->liftChild); 65 postorder(p->rightChild); 66 std::cout << p->data << " "; 67 } 68 } 69 70 int bitTree::count(tree *p) 71 { 72 if (NULL == p) 73 return 0; 74 else 75 return count(p->liftChild) + count(p->rightChild) + 1; 76 } 77 78 int bitTree::findLeafNum(tree *p) 79 { 80 if (NULL == p) 81 return 0; 82 else 83 { 84 if (p->liftChild == NULL && p->rightChild == NULL) 85 return leafNum += 1; 86 else 87 { 88 findLeafNum(p->liftChild); 89 findLeafNum(p->rightChild); 90 } 91 return leafNum; 92 } 93 } 94 95 tree * bitTree::getRoot() 96 { 97 return root; 98 }