地址:
http://lintcode.com/zh-cn/problem/binary-tree-level-order-traversal/
借助队列来完成
class Solution { public: /* * @param root: A Tree * @return: Level order a list of lists of integer */ vector<vector<int>> levelOrder(TreeNode * root) { // write your code here vector<vector<int>> res; if(root==NULL) return res; queue<TreeNode*> queue; queue.push(root); while(!queue.empty()){ vector<int> cur; int len = queue.size(); while(len--){ TreeNode *tmp=queue.front(); cur.push_back(tmp->val); queue.pop(); if(tmp->left) queue.push(tmp->left); if(tmp->right) queue.push(tmp->right); } res.push_back(cur); } return res; } };
http://lintcode.com/zh-cn/problem/binary-tree-level-order-traversal-ii/
给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
这个题目是从底向上,其实类似上题,主要是因为用了vector方便很多:
class Solution { public: /* * @param root: A tree * @return: buttom-up level order a list of lists of integer */ vector<vector<int>> levelOrderBottom(TreeNode * root) { // write your code here queue<TreeNode*> queue; vector<vector<int>> res; int len; if(root==NULL) return res; queue.push(root); while(!queue.empty()){ len = queue.size(); vector<int> cur; while(len--){ TreeNode* temp = queue.front(); cur.push_back(temp->val); queue.pop(); if(temp->left){ queue.push(temp->left); } if(temp->right){ queue.push(temp->right); } } if(!cur.empty()) res.insert(res.begin(),cur); } return res; } };