LintCode 二叉树的层次遍历 II
2015-07-06 14:45
363 查看
中等 二叉树的层次遍历
II
查看运行结果
42%通过
给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
您在真实的面试中是否遇到过这个题?
Yes
样例
给出一棵二叉树
{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
按照从下往上的层次遍历为:
[ [15,7], [9,20], [3] ]
asd
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { /** * @param root : The root of binary tree. * @return : buttom-up level order a list of lists of integer */ public: vector<vector<int>> levelOrderBottom(TreeNode *root) { vector<vector<int>> res; if(root == nullptr) { return res; } vector<int> temp; queue<TreeNode*> q; stack<vector<int>> s; q.push(root); int i = 1;// points every level int j = 0;// lost point every level while(!q.empty()) { TreeNode *p = q.front(); q.pop(); if (p==nullptr) { ++j; } else { temp.push_back(p->val); q.push(p->left); q.push(p->right); } if (i == (temp.size() + j) && temp.size()!=0) { s.push(temp); temp.clear(); i*=2; j*=2; } } while(!s.empty()) { res.push_back(s.top()); s.pop(); } return res; } };
相关文章推荐
- 前后端分离的思考与实践(五)
- maven 项目出现 java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
- Linux C语言程序设计(一)——常量、变量和表达式
- quick-3.5打包apk for release版本(DOS命令行)
- 第五章 条件语句
- LNMP 环境发布项目
- pandas官方网站上《10 Minutes to pandas》的简单翻译
- VC透掉背景色
- javascript中JSON对象使用
- me21n增强BADI:ME_PROCESS_PO_CUST之process_account
- C语言入门:03.关键字、标识符、注释
- POJ1185:火炮(减少国家)
- css3学习总结3--CSS3图像边框
- FastDFS的配置、部署与API使用解读(2)以字节方式上传文件的客户端代码
- 前后端分离的思考与实践(四)
- extjs 在IE8下TreePanel第一次无法显示问题
- 【Github教程】史上最全github使用方法:github入门到精通
- 有了struts1为何还要学struts2
- [LeetCode] Power of Two
- 使用cocopods时导入没有提示的解决方法