二叉树复习
---恢复内容开始---
转载https://blog.csdn.net/xcy1193068639/article/details/81034537
结点的度:结点拥有的子树的数目
叶子结点:度为0的结点
分支结点:度不为0的结点
树的度:树中结点的最大的度
层次:根结点的层次为1,其余结点的层次等于该结点的双亲结点的层次加1
树的高度:树中结点的最大层次
森林:0个或多个不相交的树组成。对森林加上一个根,森林即成为树;删去根,树即成为森林。
1、二叉树第i层上的结点数目最多为2i-1(i>=1)
2、深度为k的二叉树至多有2k-1个结点(k>=1)
3、包含n个结点的二叉树的高度至少为(log2n)+1
4、在任意一棵二叉树中,若终端结点的个数为n0,度为2的结点数为n2,则n0=n2+1
5、如果一棵完全二叉树的结点总数为n,那么叶子结点等于n/2(当n为偶数时)或者(n+1)/2(当n为奇数时)
二叉查找树又被称为二叉搜索树。设x为二叉查找树中的一个结点,x结点包含关键字key,结点x的key值计为key[x]。如果y是x的左子树中的一个结点,则key[y]<=key[x];如果y是x的右子树的一个结点,则key[y]>=key[x]
在二叉查找树中:
(1)若任意结点的左子树不空,则左子树上所有结点的值均小于它的根结点的值。
(2)任意结点的右子树不空,则右子树上所有结点的值均大于它的根结点的值。
(3)任意结点的左、右子树也分别为二叉查找树。
(4)没有键值相等的结点。
深度优先遍历和广度优先遍历:
转载:https://www.cnblogs.com/zhangbaochong/p/5492877.html
1 #include <vector> 2 #include <iostream> 3 #include <stack> 4 #include <queue> 5 using namespace std; 6 7 struct BitNode 8 { 9 int data; 10 BitNode *left, *right; 11 BitNode(int x) :data(x), left(0), right(0){} 12 }; 13 14 void Create(BitNode *&root) 15 { 16 int key; 17 cin >> key; 18 if (key == -1) 19 root = NULL; 20 else 21 { 22 root = new BitNode(key); 23 Create(root->left); 24 Create(root->right); 25 } 26 } 27 28 void PreOrderTraversal(BitNode *root) 29 { 30 if (root) 31 { 32 cout << root->data << " "; 33 PreOrderTraversal(root->left); 34 PreOrderTraversal(root->right); 35 } 36 } 37 38 //深度优先搜索 39 //利用栈,现将右子树压栈再将左子树压栈 40 void DepthFirstSearch(BitNode *root) 41 { 42 stack<BitNode*> nodeStack; 43 nodeStack.push(root); 44 while (!nodeStack.empty()) 45 { 46 BitNode *node = nodeStack.top(); 47 cout << node->data << ' '; 48 nodeStack.pop(); 49 if (node->right) 50 { 51 nodeStack.push(node->right); 52 } 53 if (node->left) 54 { 55 nodeStack.push(node->left); 56 } 57 } 58 } 59 60 //广度优先搜索 61 void BreadthFirstSearch(BitNode *root) 62 { 63 queue<BitNode*> nodeQueue; 64 nodeQueue.push(root); 65 while (!nodeQueue.empty()) 66 { 67 BitNode *node = nodeQueue.front(); 68 cout << node->data << ' '; 69 nodeQueue.pop(); 70 if (node->left) 71 { 72 nodeQueue.push(node->left); 73 } 74 if (node->right) 75 { 76 nodeQueue.push(node->right); 77 } 78 } 79 } 80 81 int main() 82 { 83 BitNode *root = NULL; 84 Create(root); 85 //前序遍历 86 PreOrderTraversal(root); 87 //深度优先遍历 88 cout << endl << "dfs" << endl; 89 DepthFirstSearch(root); 90 //广度优先搜索 91 cout << endl << "bfs" << endl; 92 BreadthFirstSearch(root); 93 }