55.按之字形顺序打印二叉树

按之字形顺序打印二叉树
  • 参与人数:1413时间限制:1秒空间限制:32768K
  •  算法知识视频讲解

题目描述

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
《剑指offer》上介绍的方法太麻烦,用堆栈一会儿向左装数据,一会儿向右装数据。
我做的时候,每层数据都自右向左装入vector,装入返回值时再判断左右。
55.按之字形顺序打印二叉树_第1张图片
// 54.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <vector>
#include<algorithm>
using namespace::std;

struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};

class Solution {
public:
	vector<vector<int> > Print(TreeNode* pRoot) {
		vector< vector<int> > retVec;
		if (pRoot == NULL) return retVec;

		vector<TreeNode*> cur;
		vector<TreeNode*> next;
		int level = 0;

		cur.push_back(pRoot);
		while (!cur.empty() || !next.empty()) {
			vector<int> tmp;
			for (int i = 0; i < cur.size(); i++) {
				tmp.push_back(cur[i]->val);

				TreeNode* nodeTmp = cur[i];
				if (nodeTmp->right)
					next.push_back(nodeTmp->right);
				if (nodeTmp->left)
					next.push_back(nodeTmp->left);
			}

			if (level % 2 == 0){
				std::reverse(tmp.begin(),tmp.end());
			}
			retVec.push_back(tmp);

			cur.clear();
			cur = next;
			next.clear();
			++level;
		}
		return retVec;
	}

};
int _tmain(int argc, _TCHAR* argv[])
{
	TreeNode p1(1);
	TreeNode p2(2);
	TreeNode p3(3);
	TreeNode p4(4);
	TreeNode p5(5);
	TreeNode p6(6);
	TreeNode p7(7);
	TreeNode p8(8);
	TreeNode p9(9);
	TreeNode p10(10);
	TreeNode p11(11);
	TreeNode p12(12);
	TreeNode p13(13);
	TreeNode p14(14);
	TreeNode p15(15);

	p1.left = &p2;
	p1.right = &p3;

	p2.left = &p4;
	p2.right = &p5;

	p4.left = &p8;
	p4.right = &p9;

	p5.left = &p10;
	p5.right = &p11;

	p3.left = &p6;
	p3.right = &p7;

	p6.left = &p12;
	p6.right = &p13;

	p7.left = &p14;
	p7.right = &p15;

	Solution s;
	vector<vector<int>> result = s.Print(&p1);
	return 0;
}


你可能感兴趣的:(55.按之字形顺序打印二叉树)