1. 程式人生 > >順序儲存的前序遍歷(二叉樹)

順序儲存的前序遍歷(二叉樹)

1.題目:

Problem Description

給你一個採用順序儲存結構的二叉樹,請你設計一個演算法求出它的前序遍歷。

Input

輸入資料有多組,每組的第一行為一個正數n,表示該二叉樹的節點個數。
接下來有n個字元,表示各個位置上的元素,當字元為'#'時表示當前節點為空。

Output

輸出該二叉樹的前序遍歷

Sample Input

6
ABCDEF
6
ABC#DE

Sample Output

ABDECF
ABDCE

2.參考程式碼:

#include <iostream>
using namespace std;

char str[1111];

void PreOrder(int i,int n){
	if(str[i]!='#')
		cout<<str[i];
	if(2*i<=n)
		PreOrder(2*i,n);   ///遍歷左孩子
	if(2*i+1<=n)
		PreOrder(2*i+1,n);   ///遍歷右孩子
}

int main()
{
	int n;
	while(cin>>n)
	{
		cin>>str+1;
		PreOrder(1,n);
		cout<<endl;
	}
	return 0;
}