How to print a python binary tree from the top
Today, I will talk to you about how to print python binary trees from the top. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
0x01, brief description of the problem
Each node of the binary tree is printed from top to bottom, and the nodes on the same layer are printed from left to right.
0x02, exampl
For example: given binary tree: [3pc9re20rect nullrecovernullrew15re7]
3 /\ 9 20 /\ 15 7 returns:
[3,9,20,15,7]
0x03, the idea of problem solving is based on the characteristics of binary tree and the structure of the queue.
0x04, problem solving procedure
Import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue
Public class LevelOrderTest3 {public static void main (String [] args) {TreeNode T1 = new TreeNode (3); TreeNode T2 = new TreeNode (9); TreeNode T3 = new TreeNode (20); TreeNode T4 = new TreeNode (15); TreeNode T5 = new TreeNode (7); t1.left = T2; t1.right = T3; t3.left = T4; t3.right = T5 Int [] levelOrder = levelOrder (T1); for (int num: levelOrder) {System.out.print (num + "\ t");}
}
Public static int [] levelOrder (TreeNode root) {if (root = = null) {return new int [0];} Queue queue = new LinkedList (); queue.add (root); List list = new ArrayList (); while (! queue.isEmpty ()) {TreeNode node = queue.poll (); list.add (node.val) If (node.left! = null) {queue.add (node.left);} if (node.right! = null) {queue.add (node.right);}} System.out.println ("list =" + list); int [] result = new int [list.size ()] For (int I = 0, size = list.size (); I < size; iTunes +) {result [I] = list.get (I);} return result;}}
0x05, photo version of the problem solving program
After reading the above, do you have any further understanding of how to print python binary trees from above? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.