Java Data Structure series-tree (2): Implementation of Binary Trees and Common Operations

Source: Internet
Author: User

Java Data Structure series-tree (2): Implementation of Binary Trees and Common Operations

package tree.binarytree;public class BiTreeNode {int data;BiTreeNode leftNode;BiTreeNode rightNode;public BiTreeNode(){leftNode=null;rightNode=null;}public BiTreeNode(int data,BiTreeNode leftNode,BiTreeNode rightNode){this.data=data;this.leftNode=leftNode;this.rightNode=rightNode;}}

**************************************** ***************************************

Package tree. binarytree; public class BiTree {public BiTreeNode root; // root node public BiTree () {// empty tree this. root = null;} // input data field, left subtree, right subtree Construct binary tree public BiTree (int data, BiTree leftchild, BiTree rightchild) {BiTreeNode left, right; if (leftchild = null) {left = null;} else {left = leftchild. root;} if (rightchild = null) {right = null;} else {right = rightchild. root;} this. root = new BiTreeNode (data, left, right);} // insert the public void insert (int Data) {BiTreeNode newNode = new BiTreeNode (data, null, null); BiTreeNode current = root; // current node BiTreeNode parent; // parent node if (root = null) {root = newNode; return;} else {while (true) {parent = current; if (current. data> data) {current = current. leftNode; if (current = null) {parent. leftNode = newNode; return ;}} else {current = current. rightNode; if (current = null) {parent. rightNode = newNode; return ;}}}// search for public BiTreeNode find (int data) {if (root = null) {throw new RuntimeException ("binary unknown blank");} BiTreeNode current = root; while (current. data! = Data) {if (current. data> data) {current = current. leftNode;} else {current = current. rightNode;} if (current = null) {return null ;}} return current ;}}


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.