Look at a specific exercise practice:
topic
According to the sequence of the preliminary sequence of the binary tree, such as: 7, -7,8,#, -3,6,#, 9, 9,#, -5,#,#, Order and post -order traversal
Code
Import java.util.Scanner; Public Class Binarytree {Public Static String [] str; Public Static Int Count; / *** Static internal class, define the binary tree node* / static class E {Public String Data; Treenode LChild; Treenode Rchild; Public Treenode (String X) {This.data = x;} / ** * Construct a binary tree to construct a binary tree according to the preliminary sequence column * * @Return * / PUBLIC TREENODE CREATEBTREE () {Treenode Root = Null; if (Count> = STR .length || Str [Count ++]. Equals ("#") {root = null;} else {root = new timeode (str [count- 1]); root.lchild = createBtree (); = CreateBtree ();} Return Root;} / ** * Live sequentially * * @param root * / public static void pretraverse (Treenode root) {if (root! = NULL) {SYSEM.OUT.PRINT (root.d ATA + " "); Pretraverse (root.lchild); Pretraverse (root.rchild);} / ** * preface * * * * * @param root * / Public Static void Intraverse (Treenode Root) {if (root! = null) { Intraverse (root.lchild); System.out.print (root.data + ""); intraverse (root.rchild);} / ** * Live sequence of * * @Param Root * / PUBLIC Static d postraverse (timely root) {if (root! = Null) {posttraverse (root.lchild); posttraverse (root.rchild); systers.out.print (root.data + ""); ain (String ARGS [] ) {Scanner Cin = New Scanner (System.in); While (cin.hasnext ()) {string s = cin.nextline (); str = s.split (","); count = 0; time of root = ceateBtree (); // The preliminary sequence traversed the pretraverse (root); the system.out.println (); // The order of intraverse (root); system.out.println (); .out.println ();}}}
The depth of binary tree
The following is the realization of the recursive algorithm of the binary tree. The idea is that if it is empty, its depth is 0. Otherwise, its depth is equal to the maximum value of the depth of the left subtree and the right tree.
class node {string name; node left; node right; public node (string name) {this.Name = name;} @Override Public String TostRing () e;}} // Define the binary tree class binarytree {node root; public Binarytree () {root = null;} // For the sake of convenience, I will directly write a initialized binary tree. For details, you can see the previous log public void inittree () {node node1 = new node ("a"); node node2 = new node ("b"); node node3 = new node ("c"); node node4 = new node ("d"); node node5 = new node ("e"); root = node1.let1; node2; node2.right = node3; node1.right = node4; node3.left = node5;} // Find the depth of the binary tree (node root) {int depth1; int depth2; if (roo t == null) Return 0; // The depth depth1 = length (root.richt); // The depth depth2 = length (root.left); if (depth1> depth2) Return depth1+1; } } Public class testmatch {Public Static void main (string [] art) {binarytree tree = new binarytree (); tree.inittree (); e.root);}}