[LeetCode]Binary Tree Level Order Traversal II
发布日期:2021-11-22 02:48:49 浏览次数:4 分类:技术文章

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

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},

3   / \  9  20    /  \   15   7

return its bottom-up level order traversal as:

[  [15,7],  [9,20],  [3]]

题解:采用的是bfs+queue,queue使用list来模拟的,jdk1.8       LinkedList没有实现Queue,最后用Collections.reverse(list)反转,用parentSize和childSize来统计一行的节点数。

code:

public List
> levelOrderBottom(TreeNode root) { List
> level = new ArrayList
>(); List
con = new ArrayList
(); TreeNode temp; int parentSize=1; int childSize=0; List
q = new LinkedList
(); q.add(root); do{ temp = q.get(0); con.add(temp.val); q.remove(0); if(temp.left!=null){ q.add(temp.left); childSize++; } if(temp.right!=null){ q.add(temp.right); childSize++; } parentSize--; if(parentSize ==0){ level.add(con); parentSize = childSize; childSize=0; con = new ArrayList
(); } }while(!q.isEmpty()); Collections.reverse(level); return level; }

转载地址:https://blog.csdn.net/zxdfc/article/details/48623885 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:[LeetCode]Plus One
下一篇:Spring 自动扫描组件

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月01日 01时33分20秒