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,#,#,15,7} ,
3 / 9 / 7
Return its level order traversal as:
[ 3], [9,20], [15,7]]
Confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
OJ ' s Binary Tree serialization:
The serialization of a binary tree follows a level order traversal, where ' # ' signifies a path terminator where no node ex Ists below.
Here's an example:
1 / 2 3 / 4 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}". Test instructions: The hierarchical traversal of the tree.
Idea: The use of the queue to deal with the line, each record is queued to a few, is the next level to access the
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;} *} */public class Solution {public list<list<integer>> levelorder (TreeNode ro OT) {list<list<integer>> result = new arraylist<list<integer>> (); Result.clear (); if (root = null) return result; linkedlist<treenode> q = new linkedlist<treenode> (); Q.add (root); int level = 0, count = 1; while (!q.isempty ()) {list<integer> tmp = new arraylist<integer> (); Tmp.clear (); level = 0; for (int i = 0; i < count; i++) {root = Q.pollfirst (); Tmp.add (Root.val); if (root.left! = null) {Q.add (root.left); ++level; } if (root.right! = null) {Q.add (root.right); ++level; }} count = level; Result.add (TMP); } return result; }}
Leetcode Binary Tree level Order traversal