The beauty of Java [from cainiao to masters]: Data Structure basics tree and binary tree

Source: Internet
Author: User

Implementation of Binary Tree in Java interview book

Author: Egg

Email: xtfggef@gmail.com

Weibo: http://weibo.com/xtfggef

Blog: http://blog.csdn.net/zhangerqing (reprinted please explain the source)

We will continue to explain the data structure in the previous article. This chapter describes the data structure tree and binary tree. From this chapter, we will introduce the non-linear structure, which is a little more difficult to understand than linear tables. I try to write it more commonly, if you have any questions during the reading process, please contact me through the above methods!

I. Tree

Tree structure is an important non-linear structure. A tree structure is a structure with branches and hierarchical relationships between nodes. It is very similar to a tree in nature. Tree structures exist in a large number in the objective world, such as genealogy and administrative organizations. Tree is also widely used in the computer field. For example, in compiling a program, a tree is used to represent the syntax structure of the source program. In the database system, a tree can be used to organize information; when analyzing the behavior of an algorithm, you can use a tree to describe its execution process. This chapter focuses on the storage representation and various operations of Binary Trees, studies the Conversion Relationship between General trees and forests and binary trees, and finally introduces the application example of the tree.

Ii. Binary Tree

A binary tree (binarytree) is a finite set of n (n ≥ 0) nodes. It is also an empty set (n = 0 ), it may also be composed of a root node and a binary tree of two left and right sub-trees separated from each other. For more concepts, please search for them online. Here we will use code to implement common algorithms. For more concepts, visit: http://student.zjzk.cn/course_ware/data_structure/web/SHU/shu6.2.3.1.htm.

1. Create a binary tree

First, we use a generalized table to establish a binary tree (on the concept of generalized table, please refer to the introduction of Encyclopedia: http://baike.baidu.com/view/203611.htm)

We create a string-Type Generalized table as the input:

String expression = "A (B (D (, G), C (E, F)"; the binary tree corresponding to the generalized table is:


Before writing code, we can observe the binary tree and generalized table to draw some conclusions:

  • Each time a letter is encountered, a node will be created
  • Whenever you encounter "(", you need to create the left child node on the surface.
  • Whenever "," indicates that you want to create a child node
  • When ")" is encountered, it indicates that the previous node is returned.
  • The number of "(" in a generalized table is exactly the number of layers of a binary tree.

Based on these conclusions, we can basically start writing code. First, we recommend a node class (which also belongs to a custom data structure ).

package com.xtfggef.algo.tree;public class Node {private char data;private Node lchild;private Node rchild;public Node(){}public char getData() {return data;}public void setData(char data) {this.data = data;}public Node getRchild() {return rchild;}public void setRchild(Node rchild) {this.rchild = rchild;}public Node getLchild() {return lchild;}public void setLchild(Node lchild) {this.lchild = lchild;}public Node(char ch, Node rchild, Node lchild) {this.data = ch;this.rchild = rchild;this.lchild = lchild;}public String toString() {return "" + getData();}}

The code for creating a binary tree based on a generalized table is as follows:

public Node createTree(String exp) {Node[] nodes = new Node[3];Node b, p = null;int top = -1, k = 0, j = 0;char[] exps = exp.toCharArray();char data = exps[j];b = null;while (j < exps.length - 1) {switch (data) {case '(':top++;nodes[top] = p;k = 1;break;case ')':top--;break;case ',':k = 2;break;default:p = new Node(data, null, null);if (b == null) {b = p;} else {switch (k) {case 1:nodes[top].setLchild(p);break;case 2:nodes[top].setRchild(p);break;}}}j++;data = exps[j];}return b;}

It is not difficult to think about it. Based on the above theory, you can simply go through the program through the breakpoint!

2. Recursive traversal of Binary Trees

There are three types of binary tree traversal: first, middle, and last. Each type is divided into recursion and non-recursion. Recursive Programs are difficult to understand, but easy to implement. For the preceding Binary Tree:

A first-order traversal

A B d G C E F

Sequential traversal of B

D g B A E C f

C Post-order traversal

G d B E F C

Recursive traversal of the first, middle, and last order is as follows:

/** * pre order recursive *  * @param node */public void PreOrder(Node node) {if (node == null) {return;} else {System.out.print(node.getData() + " ");PreOrder(node.getLchild());PreOrder(node.getRchild());}}/** * in order recursive *  * @param node */public void InOrder(Node node) {if (node == null) {return;} else {InOrder(node.getLchild());System.out.print(node.getData() + " ");InOrder(node.getRchild());}}/** * post order recursive *  * @param node */public void PostOrder(Node node) {if (node == null) {return;} else {PostOrder(node.getLchild());PostOrder(node.getRchild());System.out.print(node.getData() + " ");}}

Recursive traversal of Binary Trees is easy to implement. The key is non-recursive traversal, which is difficult. See the following code:

3. Non-recursive traversal of Binary Trees

First-order non-recursive traversal:

public void PreOrderNoRecursive(Node node) {Node nodes[] = new Node[CAPACITY];Node p = null;int top = -1;if (node != null) {top++;nodes[top] = node;while (top > -1) {p = nodes[top];top--;System.out.print(p.getData() + " ");if (p.getRchild() != null) {top++;nodes[top] = p.getRchild();}if (p.getLchild() != null) {top++;nodes[top] = p.getLchild();}}}}

Principle: With a stack, the first traversal is the first traversal of the root, first the root into the stack, and then the stack, all the elements of the stack print the value, before the stack top ++, top after stack exit -- based on the principle of first-in-first-out after stack, the right node goes into the stack before the left node. After the root node goes out of the stack, it starts to process the left subtree and then the right subtree, readers and friends can go through the program and check it by themselves. It is not difficult to understand!

Non-recursive traversal in the middle order:

public void InOrderNoRecursive(Node node) {Node nodes[] = new Node[CAPACITY];Node p = null;int top = -1;if (node != null)p = node;while (p != null || top > -1) {while (p != null) {top++;nodes[top] = p;p = p.getLchild();}if (top > -1) {p = nodes[top];top--;System.out.print(p.getData() + " ");p = p.getRchild();}}}

Principle omitted.

Subsequent non-recursive traversal:

public void PostOrderNoRecursive(Node node) {Node[] nodes = new Node[CAPACITY];Node p = null;int flag = 0, top = -1;if (node != null) {do {while (node != null) {top++;nodes[top] = node;node = node.getLchild();}p = null;flag = 1;while (top != -1 && flag != 0) {node = nodes[top];if (node.getRchild() == p) {System.out.print(node.getData() + " ");top--;p = node;} else {node = node.getRchild();flag = 0;}}} while (top != -1);}}

Iii. Tree and binary tree Conversion

I have summarized the following:

If you have other knowledge about this concept, read it online.

Author: Egg

Email: xtfggef@gmail.com

Weibo: http://weibo.com/xtfggef

Blog: http://blog.csdn.net/zhangerqing (reprinted please explain the source)

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.