题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路
【C++解法】
/*
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>> res;
queue<TreeNode*> q;
if(pRoot) q.push(pRoot);
while(!q.empty()) {
int len = q.size();
vector<int> tmp(len);
for(int i=0; i<len; ++i) {
TreeNode *p = q.front(); q.pop();
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
tmp[i] = p->val;
}
res.push_back(tmp);
}
return res;
}
};
【Java解法】
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer> > ();
Queue<TreeNode> q = new LinkedList<>();
if (pRoot != null) {q.add(pRoot);}
while (!q.isEmpty()) {
ArrayList<Integer> tmp = new ArrayList<>();
int len = q.size();
while (len-- > 0) {
TreeNode p = q.poll();
if (p.left != null) {q.add(p.left);}
if (p.right != null) {q.add(p.right);}
tmp.add(p.val);
}
res.add(tmp);
}
return res;
}
}
参考文献