有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。
C++实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class TreePrinter {
public:
vector< vector<int> > printTree(TreeNode* root) {
// write code here
vector< vector<int> > results;
queue<TreeNode *> myq;
myq.push(root);
struct TreeNode * temp;
struct TreeNode * nlast = root;
struct TreeNode* last = root;
vector<int> temp_row;
while (!myq.empty()) {
temp = myq.front();
if (temp->left) {
myq.push(temp->left);
nlast = temp->left;
}
if (temp->right) {
myq.push(temp->right);
nlast = temp->right;
}
temp_row.push_back(temp->val);
if (temp==last) {
results.push_back(temp_row);
temp_row.clear();
last = nlast;
}
myq.pop();
}
return results;
}
};
Python 实现
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class TreePrinter:
def printTree(self, root):
# write code here
q, row , results = [],[],[]
last, nlast = root, root
q.append(root);
while q:
tmp = q.pop(0)
if tmp.left:
q.append(tmp.left)
nlast = tmp.left
if tmp.right:
q.append(tmp.right)
nlast = tmp.right
row.append(tmp.val)
if last == tmp:
last = nlast
results.append(row)
row = []
return results