码迷,mamicode.com
首页 > 编程语言 > 详细

【Java】二叉树(Binary Tree)重温

时间:2015-07-06 15:46:43      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

距离上次使用二叉树快有一年的时间了,是时候重温一次了。

【二叉树的定义】

二叉树是层次结构,要么是空集,要么是由一个成为根的元素和两颗不同的子二叉树组成(递归定义,子二叉树也可能是空集)。

两个子二叉树分别称为左子树和右子树。一个节点的左子树的根节点称为该节点的左孩子,没有孩子的点称为叶节点。

二叉查找树的特点是,每一个节点左子树中节点的值都小于该节点的值,右子树中节点的值都大于该点。

下面是我定义的数据结构:

 1 /**
 2  * Created by 天河 on 2015/7/6.
 3  */
 4 //自己实现的BinaryTree
 5 public class MyBTree {
 6     private Object element = null;
 7     private MyBTree left = null;
 8     private MyBTree right = null;
 9     public MyBTree(Object o) {
10         element = o;
11     }
12     public void setElement(Object o) {
13         element = o;
14     }
15     public void setLeft(MyBTree o) {
16         left = o;
17     }
18     public void setRight(MyBTree o) {
19         right = o;
20     }
21 }

 

 

 这里将成员变量设置为私有的,可能会影响后续的使用,不过先试一试好了。

【插入元素】

算法:如果二叉树是空的,则使用新元素创建一个根节点;否则,为新元素寻找父节点。如果新元素的值小于父节点的值,则将新元素的节点设置为父节点的左孩子;否则将其设为右孩子。

这里我使用了递归的方式,代码如下:

 1 public class Main {
 2     public static void main(String[] args) {
 3         MyBTree root = null;
 4         root = insertElement(50, root);
 5         root = insertElement(30, root);
 6         root = insertElement(60, root);
 7         root = insertElement(30, root);
 8     }
 9     static MyBTree insertElement(int o, MyBTree t) {
10         if(t == null) {
11             t = new MyBTree(o);
12         }
13         else {
14             //Locate the parent node, and insert the node by recursion
15             MyBTree current = t;
16             while(current != null) {
17                 if(o < current.getElement()) {
18                     insertElement(o, current.getLeft());
19                 }
20                 else if(o > current.getElement()) {
21                     insertElement(o, current.getRight());
22                 }
23                 else {
24                     System.out.println("There is already this element in your binary tree");
25                     break;
26                 }
27             }
28         }
29         return t;
30     }
31 }

 

但是点击了运行之后却出现了尴尬的结果——没有执行。调试后我发现是因为函数调用产生的问题:Java是传值调用,也就意味着我对函数内结点的操作不能添加到原来的实例上。

对于此问题,我想出了几种解决办法:

1.

 

【Java】二叉树(Binary Tree)重温

标签:

原文地址:http://www.cnblogs.com/solare/p/4624255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!