本文共 1128 字,大约阅读时间需要 3 分钟。
文章作者:Tyan
博客: | |Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree[3,9,20,null,null,15,7]
, 3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7]]
这个题就是一个树的层次遍历问题,需要用到新的数据结构队列,把每一层的结点的子结点放入到队列中,依次遍历。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List
> levelOrder(TreeNode root) { List
> list = new ArrayList
>(); if(root == null) { return list; } Queue queue = new LinkedList (); queue.add(root); Queue result = new LinkedList (); List level = new ArrayList (); while(!queue.isEmpty()) { TreeNode temp = queue.poll(); level.add(temp.val); if(temp.left != null) { result.add(temp.left); } if(temp.right != null) { result.add(temp.right); } if(queue.isEmpty()) { queue = result; result = new LinkedList (); list.add(level); level = new ArrayList (); } } return list; }}
转载地址:http://mdwui.baihongyu.com/