剑指offer-从上往下打印二叉树

2016/05/24 C和C++基础

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

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

vector<int> PrintFromTopToBottom(TreeNode *root){
	vector<int> vec;
	if(root!=NULL){
		queue<TreeNode*> q;
		vec.push_back(root->val);
		q.push(root);
		while(!q.empty()){
			int s=q.size();
			for(int i=0;i<s;i++){
				TreeNode *temp=q.front();
				if(temp->left!=NULL){
					vec.push_back(temp->left->val);
					q.push(temp->left);
				}
				if(temp->right!=NULL){
					vec.push_back(temp->right->val);
					q.push(temp->right);
				}
				q.pop();
			}
		}
	}
	return vec;
}

void printTree(TreeNode *T){
	if(T!=NULL){
		cout<<T->val<<" ";
		printTree(T->left);
		printTree(T->right);
	}
}

int main(){
	TreeNode n1(1),n2(2),n3(3),n4(4),n5(5),n6(6),n7(7);
	TreeNode *root=&n1;
	n1.left=&n2;
	n1.right=&n3;
	n2.left=&n4;
	n2.right=&n5;
	n3.left=&n6;
	n3.right=&n7;
	PrintFromTopToBottom(root);
	system("pause");
}

Search

    Post Directory