[LeetCode-interview algorithm classic-Java implementation] [102-Binary Tree Level Order Traversal (Binary Tree sequence Traversal)], leetcode -- java
[102-Binary Tree Level Order Traversal (Binary Tree sequence Traversal )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
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 20 / \ 15 7
Return its level order traversal:
[ [3], [9,20], [15,7]]
Theme
Given a binary tree, It outputs the nodes of each layer.
Solutions
Use two queues: one to save the current processing layer and the other to save the next processing layer. Only process each layer.
Code Implementation
Tree node class
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
Algorithm Implementation class
import java.util.ArrayList;import java.util.Deque;import java.util.LinkedList;import java.util.List;public class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) { return result; } Deque<TreeNode> cur = new LinkedList<>(); Deque<TreeNode> sub = new LinkedList<>(); Deque<TreeNode> exc; TreeNode node; cur.addLast(root); while (!cur.isEmpty()) { List<Integer> layout = new LinkedList<>(); while (!cur.isEmpty()) { node = cur.removeFirst(); layout.add(node.val); if (node.left != null) { sub.addLast(node.left); } if(node.right != null) { sub.addLast(node.right); } } exc = cur; cur = sub; sub = exc; result.add(layout); } return result; }}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/47354349]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.