二叉树的层序遍历
1 void LevelorderTraversal(BinTree BT) 2 { 3 std::queue<BinTree> Queue; 4 BinTree T; 5 if (!BT) 6 return; //若是空树则直接返回 7 Queue.push(BT); 8 while (!Queue.empty()) 9 { 10 T = Queue.front(); 11 Queue.pop(); 12 printf("%c ", T->Data); 13 if (T->Left) Queue.push(T->Left); 14 if (T->Right) Queue.push(T->Right); 15 } 16 }
二叉树叶节点输出算法
1 void InorderTraversal(BinTree BT, int Depth) 2 { 3 if (BT) 4 { 5 if(!BT->Left && !BT->Right) 6 printBinTree(BT, Depth); 7 InorderTraversal(BT->Left, Depth + 1); 8 InorderTraversal(BT->Right, Depth + 1); 9 10 //printf("%c", BT->Data); 11 12 } 13 }
求二叉树的高度
1 int GetHeight(BinTree BT) 2 { 3 int HL, HR, MaxH; 4 if (BT) 5 { 6 HL = GetHeight(BT->Left); //求左子树的高度 7 HR = GetHeight(BT->Right); //求右子树的高度 8 MaxH = HL > HR ? HL : HR; //取左右子树较大的高度 9 return (MaxH + 1); //返回树的高度 10 } 11 else 12 return 0; 13 }
层序创建一棵二叉树
1 BinTree CreateBinTree() 2 { 3 ElementType dt; 4 BinTree BT, T; 5 std::queue<BinTree> Q; 6 scanf_s("%c", &dt); 7 getchar(); 8 if (dt != NoInfo) 9 { 10 BT = (BinTree)malloc(sizeof(struct TNode)); 11 BT->Data = dt; 12 BT->Left = BT->Right = NULL; 13 Q.push(BT); 14 } 15 else 16 return NULL; 17 while (!Q.empty()) 18 { 19 T = Q.front(); 20 Q.pop(); 21 scanf_s("%c", &dt); 22 getchar(); 23 if (dt == NoInfo) 24 T->Left = NULL; 25 else 26 { 27 T->Left = (BinTree)malloc(sizeof(struct TNode)); 28 T->Left->Data = dt; 29 T->Left->Left = T->Left->Right = NULL; 30 Q.push(T->Left); 31 } 32 scanf_s("%c", &dt); 33 getchar(); 34 if (dt == NoInfo) 35 T->Right = NULL; 36 else 37 { 38 T->Right = (BinTree)malloc(sizeof(struct TNode)); 39 T->Right->Data = dt; 40 T->Right->Left = T->Right->Right = NULL; 41 Q.push(T->Right); 42 } 43 } 44 return BT; 45 }