2

leetCode解题报告之Binary Tree Level Order Traversal II,I(二叉树层次遍历)

 3 years ago
source link: https://blog.csdn.net/ljphhj/article/details/22428939
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
leetCode解题报告之Binary Tree Level Order Traversal II,I(二叉树层次遍历)_快乐de胖虎-CSDN博客

题目:

Binary Tree Level Order Traversal II(由于Binary Tree Level Order Traversal I 这个题目只是在II的基础上少了一步最后的翻转result list而已,所以我就不贴出它的代码了)

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

return its bottom-up level order traversal as:

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

分析:

其实就是二叉树的层次遍历,但是需要把每个层次的数放入到一个ArrayList<Integer>中,最后得到一个存放所有层次结果集合的大集合ArrayList<ArrayList<Integer>> list.

解题思路:

居然要层次遍历,那么我们如果一层层放入到queue中,然后取出这一层结点,并把值放入到一个ArrayList<Integer>中,并加入到最终集合list中,接着我们把这一层的孩子结点,即下一层的结点再放入到queue中,这样直到queue为empty的时候,我们便把所有层次都遍历完毕了,这样子我们将 list 进行翻转,便得到了题目想要的结果了!!

AC代码1:(436ms)

AC代码2(网友提供):(472ms)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK