ImportJava.util.ArrayDeque; Public classBinaryTree {Static classtreenode{intvalue; TreeNode left; TreeNode right; PublicTreeNode (intvalue) { This. value=value; }} TreeNode root; PublicBinaryTree (int[] Array) {Root=makebinarytreebyarray (array,1); } /*** Recursive way to create a binary tree * An array representation of a two-fork tree is constructed * Two-fork linked list representation with two-fork tree*/ Public StaticTreeNode Makebinarytreebyarray (int[] Array,intindex) { if(index<array.length) { intValue=Array[index]; if(value!=0) {TreeNode T=NewTreeNode (value); Array[index]=0; T.left=makebinarytreebyarray (array,index*2); T.right=makebinarytreebyarray (array,index*2+1); returnT; } } return NULL; } /*** Depth-first traversal, equivalent to root traversal * with non-recursive implementation * requires auxiliary data structure: Stack*/ Public voiddepthordertraversal () {if(root==NULL) {System.out.println ("Empty Tree"); return; } arraydeque<TreeNode> stack=NewArraydeque<treenode>(); Stack.push (root); while(Stack.isempty () = =false) {TreeNode node=Stack.pop (); System.out.print (Node.value+" "); if(node.right!=NULL) {Stack.push (node.right); } if(node.left!=NULL) {Stack.push (node.left); }} System.out.print ("\ n"); } /*** Breadth-FIRST traversal * adopts non-recursive implementation * requires auxiliary data structure: Queue*/ Public voidlevelordertraversal () {if(root==NULL) {System.out.println ("Empty Tree"); return; } arraydeque<TreeNode> queue=NewArraydeque<treenode>(); Queue.add (root); while(Queue.isempty () = =false) {TreeNode node=Queue.remove (); System.out.print (Node.value+" "); if(node.left!=NULL) {queue.add (node.left); } if(node.right!=NULL) {queue.add (node.right); }} System.out.print ("\ n"); } /*** 13 */* 65 5 */\ * *//\/* 4*/ Public Static voidMain (string[] args) {int[] arr={0,13,65,5,97,25,0,37,22,0,4,28,0,0,32,0}; BinaryTree Tree=NewBinaryTree (arr); Tree.depthordertraversal (); Tree.levelordertraversal (); }}
Horizontal traversal and vertical traversal of trees
The principle of depth-first traversal and breadth-first traversal of a tree and Java implementation Code