码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树,添加,查找

时间:2014-05-07 18:45:42      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   color   

bubuko.com,布布扣
public class Tree {
    
    TreeNode last = null;
    TreeNode root = null;
    
    
    public Tree(int value){
        root = createNode(value);
    }
        
    //结构
     static class TreeNode{
         int data;
         TreeNode left;
         TreeNode right; 
     }
     
     //查找结点
     public boolean searchTreeNode(int key,TreeNode tree){
         if(tree == null){
             return false;
         }
         if(tree.data == key){
             return true;
         }else if(tree.data > key){
             last = tree;
             searchTreeNode(key,tree.left);
         }else if(tree.data < key){
             last = tree;
             searchTreeNode(key,tree.right);
         }
         return false;
     }
     
     
     //添加节点
     public void addTreeNode(int key){
         if(!searchTreeNode(key,root)){
             TreeNode tree = createNode(key);
             if(key < last.data){
                 last.left = tree;
             }else if(key>last.data){
                 last.right = tree;
             }
         }
         last = null;
     }
     
     //遍历
     public void iterate(TreeNode node){
        if(node ==null){
            return;
        }
        System.out.println(node.data);
        iterate(node.left);
        iterate(node.right);
     }
    
     public TreeNode createNode(int key){
        TreeNode tree = new TreeNode();
        tree.data = key;
        return tree;
     }
     
     public void removeNode(int key){
         
     }
     
     public static void main(String[] args){
         Tree tree = new Tree(4);
         tree.addTreeNode(5);
         tree.addTreeNode(6);
         tree.addTreeNode(3);
         tree.addTreeNode(7);
         tree.addTreeNode(8);
         tree.addTreeNode(9);
         tree.iterate(tree.root);
     }
     
}
bubuko.com,布布扣

 

二叉树,添加,查找,布布扣,bubuko.com

二叉树,添加,查找

标签:style   blog   class   code   java   color   

原文地址:http://www.cnblogs.com/JimmyXie/p/3709827.html

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