Topic
two hierarchical traversal of a fork tree
Gives a binary tree that returns the hierarchical traversal of its node value (accessed from left to right)
Sample Example
To a two-pronged tree {3,9,20,#,#,15,7} :
3 / 9 20 / 15 7
Returns the result of his layered traversal:
[ [3], [9,20], [15,7]]
challenges
Challenge 1: Use only one queue to implement it
Challenge 2: Use the DFS algorithm to do
Solving
Queue is easy, first join, and then take out the same time to join the left and right child node
There is a topic in the sword offer which is similar to this one, it is only a hierarchical traversal of the binary tree, and there is no requirement to put the nodes of each layer together separately.
The above-mentioned rule: each time a node is printed, if the nodes have child nodes, then the node's sub-node is placed in the tail of a queue. Next to the head of the queue take out the first node to enter the queue.
Repeat the previous print operation until all the nodes in the queue are printed.
Above is the level of printing all nodes, instead of each layer of nodes placed in a list output, so the queue holds the elements of the current layer.
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot:the root of binary tree. * @return: Level order A list of lists of integers*/ PublicArraylist<arraylist<integer>>Levelorder (TreeNode root) {//Write your code herequeue<treenode> queue =NewLinkedlist<treenode>(); ArrayList<ArrayList<Integer>> tree =NewArraylist<arraylist<integer>>(); if(Root = =NULL) returnTree; Queue.offer (root); while(!Queue.isempty ()) {ArrayList<Integer> list =NewArraylist<integer>(); intSize =queue.size (); for(inti=0;i<size;i++) {TreeNode head=Queue.poll (); List.add (Head.val); if(head.left!=NULL) {queue.offer (head.left); } if(head.right!=NULL) {queue.offer (head.right); }} tree.add (list); } returnTree; }}Java Code
DFS programs, see chapter IX
Lintcode Medium: Binary tree Level order traversal two traversal of the number of forks