& Lt; Basic consolidation & gt; binary tree traversal

Source: Internet
Author: User

Introduction:

Here we will review the basic operations of the binary tree. Here we assume that we define an ordered binary tree, that is, for any node, if there is a left subnode, the value of the Left subnode must be smaller than this node, if there is a right child node, the value of the right child node must be greater than that node. Here we also show the code to show how to traverse the binary tree in the forward, middle, and backward directions.


Practice:

First, we define a binary tree node class:

Package com. charles. algo. binarytree;/*** this class defines a binary tree node * @ author charles. wang **/public class BinaryTreeNode {// the content of the current node in the binary tree is private Object data; // The left subnode of the binary tree is private BinaryTreeNode leftChild; // The right subnode of the binary tree is private BinaryTreeNode rightChild; public BinaryTreeNode (Object data, BinaryTreeNode leftChild, BinaryTreeNode rightChild) {this. data = data; this. leftChild = leftChild; this. rightChild = rightChild;} public Object getData () {return data;} public void setData (Object data) {this. data = data;} public BinaryTreeNode getLeftChild () {return leftChild;} public void setLeftChild (BinaryTreeNode leftChild) {this. leftChild = leftChild;} public BinaryTreeNode getRightChild () {return rightChild;} public void setRightChild (BinaryTreeNode rightChild) {this. rightChild = rightChild ;}}


Then we define a binary tree class. This binary tree provides the insert node, pre-order traversal, middle-order traversal, and post-order traversal methods:

Package com. charles. algo. binarytree;/*** the data structure of a basic ordered binary tree is defined here * @ author charles. wang **/public class OrderedBinaryTree <T> {// you can use a linked list to store data in a binary sorting tree. The root node private BinaryTreeNode rootNode is placed here; public OrderedBinaryTree () {rootNode = null;}/*** returns the maximum height of the current ordered binary tree * @ return */public int getMaxHeight () {return getHeight (rootNode );} /*** determine the height of the subtree based on the current root node. This is a recursive method * @ return */private int getHeight (BinaryTree Node currentNode) {// if the current root Node is empty, return 0 if (currentNode = null) return 0; // if the current root Node is not empty, obtain the maximum int maxLeftTreeHeight = getHeight (currentNode. getLeftChild () + 1; int maxRightTreeHeight = getHeight (currentNode. getRightChild () + 1; return Math. max (maxLeftTreeHeight, maxRightTreeHeight);}/*** Insert the node to the current Ordered Binary Tree, */public OrderedBinaryTree insertNode (Object data) {// If the rootNode in the ordered binary tree is empty, create a new section directly. And assigned to root if (rootNode = null) {BinaryTreeNode binaryTreeNode = new BinaryTreeNode (data, null, null); rootNode = binaryTreeNode; return this ;} // If the rootNode of the ordered binary tree is not empty, call the recursive method to insert else return insertNode (data, rootNode );} /*** recursively insert a node to the current node to maintain an ordered binary tree */public OrderedBinaryTree insertNode (Object data, BinaryTreeNode rootNode) {// create a node BinaryTreeNode currentNode = new BinaryTreeNode (data, Null, null); // compare the current data with the size of the inserted rootNode // if the current data is smaller than the inserted rootNode, then, the new data node must be inserted in the if (Integer) data <(Integer) rootNode on the left of the rootNode. getData () {// if the left node of the rootNode to be inserted is empty, insert if (rootNode. getLeftChild () = null) {rootNode. setLeftChild (currentNode); return this;} // If the left node of the rotNode to be inserted is not empty, set recursive to the left node where the insertion point is set to root, then, recursively call the method to insert else return insertNode (data, rootNode. getLeftChild ();} // if the current data is greater than the inserted rootNode, the new data node must be Insert it to the right else of the rootNode {// if the right node of the rootNode to be inserted is empty, insert if (rootNode. getRightChild () = null) {rootNode. setRightChild (currentNode); return this;} // if the right node of the rootNode to be inserted is not empty, set the destination node of the gambling node to the right node of the root node, then recursively call the method to insert else return insertNode (data, rootNode. getRightChild ();}/*** traverse the binary tree in the forward order and print the nodes of the binary tree */public void preOrderFullBinaryTree () {preOrder (rootNode );} /*** traverse the binary tree in the middle order and print the nodes of the binary tree */public void midO RderFullBinaryTree () {midOrder (rootNode);}/*** traverse the binary tree in ascending order and print each node of the binary tree */public void postOrderFullBinaryTree () {postOrder (rootNode);}/*** traverses a node in the forward order. It prints the current node and then prints the node on the left, then print the right node */private void preOrder (BinaryTreeNode currentNode) {// if the current node is null, the current node is not printed and the recursive if (currentNode! = Null) {System. out. print (currentNode. getData () + ""); // traverse the left subtree preOrder (currentNode. getLeftChild (); // traverses the right subtree preOrder (currentNode. getRightChild () ;}}/*** traverses a node in the middle order. It prints the left node and then the current node, finally, print the right node * @ param args */private void midOrder (BinaryTreeNode currentNode) {// if the current node is null, the current node is not printed, and exit recursion if (currentNode! = Null) {midOrder (currentNode. getLeftChild (); System. out. print (currentNode. getData () + ""); midOrder (currentNode. getRightChild () ;}}/*** traverse a node in sequence. It prints the left node and the right node, finally, the current node * @ param args */private void postOrder (BinaryTreeNode currentNode) is printed. {// if the current node is null, the current node is not printed, and exit recursion if (currentNode! = Null) {postOrder (currentNode. getLeftChild (); postOrder (currentNode. getRightChild (); System. out. print (currentNode. getData () + "") ;}} public static void main (String [] args) {OrderedBinaryTree <Integer> fbt = new OrderedBinaryTree <Integer> (); fbt. insertNode (12 ). insertNode (5 ). insertNode (9 ). insertNode (11 ). insertNode (8 ). insertNode (42 ). insertNode (4); // traverse all nodes in the forward order System. out. println ("traverse all nodes of a binary tree in the forward order:"); fbt. preOrderFullBinaryTree (); System. out. println (); // traverse all nodes in the middle order System. out. println ("traverse all the nodes of a binary tree in the central order:"); fbt. midOrderFullBinaryTree (); System. out. println (); // traverse all nodes in the descending order of System. out. println ("post-order traversal of all nodes of a binary tree:"); fbt. postOrderFullBinaryTree (); System. out. println ();}}


In fact, considering the hierarchy of Binary Tree definitions, the above methods are implemented using recursion. For example, insertion is to compare the current element. If the number of inserted elements is less than that of the current element, then compare the left child element of the current element. If the left child element does not exist, the newly inserted element is used as the left child element. Otherwise, the left child element is taken as the root element, recursively insert this element into the left subtree. In turn, if the inserted element is larger than the current element, it takes a long time to compare the right child element of the current element. If the right child element does not exist, the newly inserted element is used as the right child element, otherwise, the right child element is taken as the root and recursively inserted into the element to the right child binary tree.


The same is true for pre-order, middle-order, and post-order traversal.


Verification Result:

Finally, let's run this simple example, Which is expected. For example, if we insert different numbers separately, then the traversal result sequence is different but all nodes of the binary tree are traversed.

650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/140112/2101405441-0.jpg "title =" 64.png" alt = "wKiom1LOW1nw9s9_AADdUvAfbdo940.jpg"/>

This article from "parallel line cohesion" blog, please be sure to keep this source http://supercharles888.blog.51cto.com/609344/1350157

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.