[Javase] Data structure (binary tree-traversal and lookup)

Source: Internet
Author: User

Pre-sequence traversal: Middle, left, right

Middle sequence traversal: Left, middle, right

Post-post traversal: Left, right, middle

Binary Tree Lookup

Compare from root node, target is smaller than root node, pointer moves to left

Compare from the root node, the target is larger than the root node, and the pointer moves to the right

    /*** Pre-order traversal *@paramTree*/     Public voidPreorder (Bstree tree) {preorder (tree.mroot); }     Public voidPreorder (Bstnode node) {if(node!=NULL) {System.out.print (Node.key+"");            Preorder (Node.left);        Preorder (node.right); }    }    /*** Middle Sequence traversal *@paramTree*/     Public voidmidorder (Bstree tree) {Midorder (tree.mroot); }     Public voidMidorder (Bstnode node) {if(node!=NULL) {midorder (node.left); System.out.print (Node.key+"");        Midorder (Node.right); }    }    /*** Post-post traversal *@paramTree*/     Public voidpostorder (Bstree tree) {postorder (tree.mroot); }     Public voidPostorder (Bstnode node) {if(node!=NULL) {postorder (node.left);            Postorder (Node.right); System.out.print (Node.key+""); }    }    /*** Binary Tree search *@paramTree *@paramKey *@return     */     PublicBstnode<t> Search (bstree<t>tree,t Key) {Bstnode<T> mroot=Tree.mroot;  while(mroot!=NULL){            intflag=Key.compareto (Mroot.key); if(flag<0) {Mroot=Mroot.left; }Else if(flag>0) {Mroot=Mroot.right; }Else{                returnMroot; }        }        returnMroot; }

        Tree.preorder (tree); // Output 312546        Tree.midorder (tree); // output 123456        Tree.postorder (tree); // Output 214653        Bstree.bstnode Node=tree.search (tree, 5);        System.out.println (Node.left.key); // Output 4

[Javase] Data structure (binary tree-traversal and lookup)

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.