package com.demo.calculate;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import com.demo.calculate.bean.BinaryTree;
import com.demo.calculate.bean.TreeNode;
public class BinarySortATreectivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binary_sort_tree);
findViewById(R.id.btn_binarySortTree).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createTree();
}
});
}
private void createTree() {
BinaryTree binaryTree = new BinaryTree();
int[] arr = new int[]{7,3,5,9,12,45,23,10};
for (int i = 0; i <arr.length ; i++) {
binaryTree.add(new TreeNode(arr[i]));
}
binaryTree.midShow();
}
}
package com.demo.calculate.bean;
public class BinaryTree {
private int value;
private TreeNode root;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public TreeNode getRoot() {
return root;
}
public void setRoot(TreeNode root) {
this.root = root;
}
public void frontShow() {
if (root!=null){
root.frontShow();
}
}
public void midShow() {
if (root!=null){
root.midShow();
}
}
public void afterShow() {
if (root!=null){
root.afterShow();
}
}
public TreeNode frontSearch(int i) {
if (root!=null){
return root.frontSearch(i);
}
return null;
}
public void deleteNode(int i) {
if (root!=null){
root.deleteNode(i);
}
}
public void add(TreeNode node){
if (root == null){
root = node;
}else{
root.add(node);
}
}
}
package com.demo.calculate.bean;
import android.util.Log;
public class TreeNode{
private int value;
private TreeNode nodeLeft;
private TreeNode nodeRight;
public void setNodeLeft(TreeNode nodeLeft) {
this.nodeLeft = nodeLeft;
}
public void setNodeRight(TreeNode nodeRight) {
this.nodeRight = nodeRight;
}
public TreeNode(int value) {
this.value = value;
}
public void midShow() {
/**
* 4 2 5 1 6 3 7
* 1 根据点是1 左节点是2 右节点是3 midShow();
* 2 根据点是2 左节点是4 右节点是5 midShow();
*/
if (nodeLeft!=null){
nodeLeft.midShow();
}
Log.i("tag",value+"");
//根节点是2 第一次的时候value是4
if (nodeRight!=null){
nodeRight.midShow();
}
}
public void add(TreeNode node) {
if (node==null){
return;
}
//判断要插入的节点的值是不是比当前节点的值小,小的话就作为左子节点
if (node.value<value){
if (nodeLeft==null){
nodeLeft = node;
}else{
nodeLeft.add(node);
}
//判断要插入的节点的值是不是比当前节点的值大,小的话就作为右子节点
}else{
if (nodeRight==null){
nodeRight = node;
}else{
nodeRight.add(node);
}
}
}
}