Personal feeling the realization of binary tree is mainly about how to construct a binary tree. The design method of constructing two-fork tree function is varied. The following program represents the node of a binary tree by defining an inner class, and then implements some basic operations of the data structure of the two-fork tree.
PackageTree; Public classBinarytree<e> { //Why use static internal classes? Non-static members of external classes cannot be accessed in static inner classes Public Static classtreenode{//E data;Object data; TreeNode left; TreeNode right; PublicTreeNode () {} PublicTreeNode (Object data) { This. data =data; } //constructs a new node with the left node as its child, right node for the child PublicTreeNode (Object data, TreeNode left, TreeNode right) { This. data =data; This. left =Left ; This. right =Right ; } } PrivateTreeNode Root;//A data field of a class that implements a two-fork tree, that is, a root node to represent a binary tree PublicBinaryTree () { This. root =NewTreeNode (); } //creates a binary tree with the specified root element PublicBinaryTree (E data) { This. root =NewTreeNode (data); } //Add a child node to a specified node PublicTreeNode AddNode (TreeNode parent, E data,Booleanisleft) { if(Parent = =NULL) Throw NewRuntimeException ("The parent node is empty, cannot add child nodes"); if(Isleft && Parent.left! =NULL) Throw NewRuntimeException ("Node has left child node, add failed"); if(!isleft && Parent.right! =NULL) Throw NewRuntimeException ("Node already has right child node, add failed"); TreeNode NewNode=NewTreeNode (data); if(isleft) Parent.left=NewNode; ElseParent.right=NewNode; returnNewNode; } Public Booleanempty () {returnRoot.data = =NULL;//determine if the binary tree is empty based on the root element } PublicTreeNode root () {if(Empty ())Throw NewRuntimeException ("Tree empty, unable to access root node"); returnRoot; } PublicE Parent (TreeNode node) {return NULL;//When a binary tree list is stored, access to the parent node needs to traverse the entire binary tree, as this is not implemented here . } //Accesses the left side of the specified node, returning the data field of its left child PublicE Leftchild (TreeNode parent) {if(Parent = =NULL) Throw NewRuntimeException ("Empty node cannot access its left child"); returnParent.left = =NULL?NULL: (E) Parent.left.data; } PublicE Rightchild (TreeNode parent) {if(Parent = =NULL) Throw NewRuntimeException ("Empty node cannot access its right child"); returnParent.right = =NULL?NULL: (E) Parent.right.data; } Public intDeep () {returnDeep (root); } Private intDeep (TreeNode node) {if(node = =NULL) return0; Else{ intLeftdeep =Deep (Node.left); intRightdeep =Deep (node.right); intmax = leftdeep > Rightdeep?Leftdeep:rightdeep; returnMax + 1; } }}
Java Implementation Two fork tree (simple version)