二叉排序树中插入节点

2018-07-19  本文已影响0人  mrjunwang

1已知有一颗二叉排序树,向树里面插入节点,如果该节点已存在(节点值相等),将节点中的count字段加一;如果不存在,将节点插入树中,并将节点的count值置为1。自行设计数据结构,插入算法并且分析算法的复杂度

public class TreeNode<T extends Comparable<T>> {
    private T value;
    private TreeNode<T> left;
    private TreeNode<T> right;
    private int count=0;
    public int compare(TreeNode<T> n){
        if(value.compareTo(n.getValue())>0){
            return 1;
        }
        else if(value.compareTo(n.getValue())<0){
            return -1;
        }
        else{
            return 0;
        }
    }
    public T getValue() {
        return value;
    }
    public void setValue(T value) {
        this.value = value;
    }
    public TreeNode<T> getLeft() {
        return left;
    }
    public void setLeft(TreeNode<T> left) {
        this.left = left;
    }
    public TreeNode<T> getRight() {
        return right;
    }
    public void setRight(TreeNode<T> right) {
        this.right = right;
    }
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    public TreeNode<T> insert(TreeNode<T>  root,TreeNode<T>  node){
        node.count=1;
        if(root==null){
            return node;
        }
        
        if(root.compare(node)==0){
                root.count=root.count+1;
                return root;
            }
        else if(root.compare(node)>0){
                if(root.left==null){
                    root.left=node;
                }
                else{
                    insert(root.left,node);
                }
            return root;    
            }
        else {
                if(root.right==null){
                    root.right=node;
                }
                else{
                    insert(root.right,node);
                }
                return root;    
            }
    }
    
    public static void main(String args[]){
        TreeNode<Integer> root=new TreeNode();
        TreeNode<Integer> root1=new TreeNode();
        root1.setValue(5);
        TreeNode<Integer> node=new TreeNode();
        node.setValue(2);
        
        root1.setLeft(node);
        TreeNode<Integer> node2=new TreeNode();
        node2.setValue(1);
        node.setLeft(node2);
        TreeNode<Integer> node3=new TreeNode();
        node3.setValue(3);
        TreeNode head=root.insert(root1, node3);
        Queue<TreeNode> que=new LinkedList();
        que.add(head);
        while(!que.isEmpty()){
            TreeNode cur=que.poll();
            System.out.println(cur.value +","+cur.count);
            if(cur.left!=null){
                que.add(cur.left);
            }
            if(cur.right!=null){
                que.add(cur.right);
            }
        }
    }

}

假设树中有N个节点,最多遍历树的高度。时间复杂度O(logN)

上一篇下一篇

猜你喜欢

热点阅读