博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【LintCode 简单】69. 二叉树的层次遍历
阅读量:4088 次
发布时间:2019-05-25

本文共 1070 字,大约阅读时间需要 3 分钟。

1.问题描述:

给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)。

2.样例:

给一棵二叉树 {3,9,20,#,#,15,7} :

3 / \9  20  /  \ 15   7

返回他的分层遍历结果:

[  [3],  [9,20],  [15,7]]
 
3.代码: /** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /*     * @param root: A Tree     * @return: Level order a list of lists of integer     */    vector
> levelOrder(TreeNode * root) { // write your code here vector
> order; queue
queue; int len; if(root == NULL) { return order; } queue.push(root); len = queue.size(); while(!queue.empty()) { vector
base; len = queue.size(); while(len--) { TreeNode *tmp=queue.front(); base.push_back(tmp->val); queue.pop(); if(tmp->left) queue.push(tmp->left); if(tmp->right) queue.push(tmp->right); } order.push_back(base); } return order; }};

转载地址:http://fouii.baihongyu.com/

你可能感兴趣的文章
《PostgreSQL技术内幕:查询优化深度探索》养成记
查看>>
剑指_复杂链表的复制
查看>>
FTP 常见问题
查看>>
Python学习笔记之数据类型
查看>>
shell 快捷键
查看>>
VIM滚屏操作
查看>>
将file文件内容转成字符串
查看>>
MODULE_DEVICE_TABLE的理解
查看>>
.net强制退出主窗口的方法——Application.Exit()方法和Environment.Exit(0)方法
查看>>
c# 如何调用win8自带的屏幕键盘(非osk.exe)
查看>>
build/envsetup.sh 简介
查看>>
编译Android4.0源码时常见错误及解决办法
查看>>
Android 源码编译make的错误处理
查看>>
启用SELinux时遇到的问题
查看>>
virbr0 虚拟网卡卸载方法
查看>>
No devices detected. Fatal server error: no screens found
查看>>
新版本的linux如何生成xorg.conf
查看>>
Linux基础教程:CentOS卸载KDE桌面
查看>>
read humor_campus
查看>>
my read work
查看>>