JAVA 实现二叉树

本文介绍了一个使用Java实现的简单单词计数程序。该程序通过读取标准输入中的文本,并利用二叉搜索树来存储和计数每个单词出现的次数。通过对输入文本逐字符解析并构建单词,最终统计结果被有序地输出。
import java.io.*;

class TreeNode
{
    String word; 
// Word being stored.
    int count = 1// Count of words seen in text.
    TreeNode left; // Left subtree reference.
    TreeNode right; // Right subtree reference.
    
    
public TreeNode (String word)
    
{
        
this.word = word;
        left 
= right = null;
    }

    
    
public void insert (String word)
    
{
        
int status = this.word.compareTo (word);
        
        
if (status > 0// word argument precedes current word
        {
            
// If left-most leaf node reached, then insert new node as
            
// its left-most leaf node. Otherwise, keep searching left.
            
            
if (left == null)
                left 
= new TreeNode (word);
            
else
                left.insert (word);
        }

        
else if (status < 0// word argument follows current word
        {
            
// If right-most leaf node reached, then insert new node as
            
// its right-most leaf node. Otherwise, keep searching right.
            
            
if (right == null)
                right 
= new TreeNode (word);
            
else
                right.insert (word);
        }

        
else
            
this.count++;
    }

}

    
public class WC
{
    
public static void main (String [] args) throws IOException
    
{
        
int ch;
        
        TreeNode root 
= null;
        
        
// Read each character from standard input until a letter
        
// is read. This letter indicates the start of a word.
        
        
while ((ch = System.in.read ()) != -1)
        
{
            
// If character is a letter then start of word detected.
            
            
if (Character.isLetter ((char) ch))
            
{
                
// Create StringBuffer object to hold word letters.
                
                StringBuffer sb 
= new StringBuffer ();
                
                
// Place first letter character into StringBuffer object.
                
                sb.append ((
char) ch);
                
                
// Place all subsequent letter characters into StringBuffer
                
// object.
                
                
do
                
{
                    ch 
= System.in.read ();
                    
                    
if (Character.isLetter ((char) ch))
                        sb.append ((
char) ch);
                    
else
                        
break;
                }

                
while (true);
                
                
// Insert word into tree.
                
                
if (root == null)
                    root 
= new TreeNode (sb.toString ());
                
else
                    root.insert (sb.toString ());
            }

        }

        
        display (root);
    }

    
    
static void display (TreeNode root)
    
{
        
// If either the root node or the current node is null,
        
// signifying that a leaf node has been reached, return.
        
        
if (root == null)
            
return;
        
        
// Display all left-most nodes (i.e., nodes whose words
        
// precede words in the current node).
        
        display (root.left);
        
        
// Display current node's word and count.
        
        System.out.println (
"Word = " + root.word + ", Count = " + root.count);
        
        
// Display all right-most nodes (i.e., nodes whose words
        
// follow words in the current node).
        
        display (root.right);
    }

}
 
 
Java语言实现二叉树通常需要定义节点结构,并实现一些基本操作,如添加元素、遍历等。 ### 定义节点结构 ```java package code.Tree; public class Node<T> { public Node<T> lChild; // 左孩子 private T data; // 数据域 public Node<T> rChild; // 右孩子 public Node() { // 构造函数,创建一个空节点 data = null; lChild = null; rChild = null; } public Node(T x) { // 重载构造函数,创建一个数据值为x的节点 data = x; lChild = null; rChild = null; } public T getData() { return data; } public void setData(T data) { this.data = data; } } ``` 上述代码定义了二叉树的节点结构,包含左孩子、数据域和右孩子[^1]。 ### 实现添加元素的方法 需要有一个`add`方法通过`root`根来添加结点,而`root`添加结点的代码可以提取出来写成方法`addNode()` [^3]。 ### 生成二叉树 二叉树包含左节点、右节点和当前节点`value`。创建时拿一个元素做根节点,把后续进来的元素与根节点比较,比根节点小且当前节点的左节点为空,放左边;不为空,继续比较;比根节点大且当前节点的右节点为空,放右边;不为空,继续比较,直到把数组元素放完,整棵树就生成了 [^4]。 ### 遍历二叉树 以中序遍历为例,在`main`方法中添加代码,当线索化二叉树后,再用原来的遍历方式会出现问题,因为原来的二叉树遍历是通过结点左右子节点为空来进行的,线索化后的二叉树将结点的左右指针都有值了。可以使用线索化的方式遍历二叉树 [^2]。 ```java // 在 ThreadeBinaryTree类 添加代码 // 遍历线索化二叉树的方法 public void threadedList() { // 定义一个变量,临时存储当前遍历的结点,从root开始 HeroNode node = root; while (node != null) { // 循环遍历找到leftType = 1 的这个结点,第一个找到的就是 8 结点 // 后面随着遍历而变化,因当leftType = 1 时,说明该结点是按照线索化 // 处理后的有效结点 while (node.getleftType() == 0) { node = node.getLeft(); } // 打印当前结点 System.out.println(node); // 如果当前结点的右指针指向的是后继结点,就一直输出 while (node.getRitghtType() == 1) { node = node.getRight(); System.out.println(node); } // 替换这个遍历的结点 node = node.getRight(); } } // 在 main方法中添加代码 // 当线索化二叉树后,再用原来的遍历方式会出现问题 // 因为原来的二叉树遍历是通过结点左右子节点为空来进行的 // 线索化后的二叉树将结点的左右指针都有值了 // threadeBinaryTree.infixOrder(); System.out.println("使用线索化的方式遍历 线索化二叉树"); threadeBinaryTree.threadedList(); // 8,3,10,1,14,6 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值