面试题整理-数组做为平衡二叉树进行访问

题目:

现在有一个数组,是排好序的。如何将其按照平衡二叉树进行打印。需要按层次遍历。

思路很简单,就是需要确定一个算法去找左子结点与右子结点。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <assert.h>
#include <iomanip>
#include <limits>
#include <map>
#include <queue>

using namespace std;
class node {
public:
	int begin, mid, end;
	node(int a, int b, int c):begin(a),mid(b),end(c){};
	node():begin(-1),mid(-1),end(-1){};
};
void tree_print(vector<int> &a) {
	const int n = a.size();
	queue<node> q;
	vector<char> rec(n, 0);

	q.push(node(0, n>>1, n)); rec[n>>1] = 1;
	q.push(node());

	while (q.size() > 1) {
		node t = q.front(); q.pop();

		if (-1 == t.begin && -1 == t.mid && -1 == t.end) {
			cout << endl;
			q.push(node());
			continue;
		}

		cout << a[t.mid] << ' ';
		int left = t.begin + ((t.mid - t.begin)>>1);
		int right = t.mid + ((t.end - t.mid)>>1);

		if (0 <= left && left < n && 0 == rec[left]) {
			q.push(node(t.begin, left, t.mid));
			rec[left] = 1;
		}
		if (0 <= right && right < n && 0 == rec[right]) {
			q.push(node(t.mid, right, t.end));
			rec[right] = 1;
		}
	}
	cout << endl;
}

int main(void) {
	vector<int> a;
	int n = 5;
	for (int i = 0; i < n; ++i) {
		a.push_back(i);
	}
	tree_print(a);
	return 0;
}

点赞