题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行
写成了平衡二叉树的程序。。。。。。。又没认真审题
1 public class Solution { 2 ArrayList<ArrayList<Integer> > Print(TreeNode root) { 3 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 4 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 5 if(root ==null) return res; 6 int layer = 0; 7 queue.add(root); 8 while(!queue.isEmpty()){ 9 ArrayList<Integer> restemp = new ArrayList<Integer>(); 10 while(restemp.size()<(1<<layer)){ //2的n次方 1<<n 11 TreeNode node = queue.remove(); 12 restemp.add(node.val); 13 if(node.left!=null) queue.add(node.left); 14 if(node.right!=null) queue.add(node.right); 15 } 16 layer++; 17 res.add(restemp); 18 } 19 return res; 20 } 21 22 }
用end 记录每层的节点数目
1 public class Solution { 2 ArrayList<ArrayList<Integer> > Print(TreeNode root) { 3 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 4 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 5 ArrayList<Integer> restemp = new ArrayList<Integer>(); 6 if(root ==null) return res; 7 int start = 0; 8 int end = 1; 9 queue.add(root); 10 while(!queue.isEmpty()){ 11 TreeNode node = queue.remove(); 12 restemp.add(node.val); 13 start++; 14 if(node.left!=null) queue.add(node.left); 15 if(node.right!=null) queue.add(node.right); 16 if(start==end){ 17 end = queue.size();//上层的大小 18 res.add(restemp); 19 restemp = new ArrayList<Integer>(); 20 start=0; 21 } 22 } 23 return res; 24 } 25 26 }
c++:20180730
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 }; 10 */ 11 class Solution { 12 public: 13 vector<vector<int> > Print(TreeNode* pRoot) { 14 15 vector<vector<int>> res ; 16 queue<TreeNode*> q; 17 if(pRoot==NULL) return res; 18 q.push(pRoot); 19 20 int size ; 21 while(!q.empty()){ 22 vector<int> temp ; 23 size = q.size(); 24 25 for(int i = 0;i<size;i++){ 26 TreeNode* root = q.front(); 27 q.pop(); 28 temp.push_back(root->val); 29 30 if(root->left!=NULL) q.push(root->left); 31 if(root->right!=NULL) q.push(root->right); 32 33 } 34 res.push_back(temp); 35 } 36 return res; 37 } 38 39 };