1已知有一顆二叉排序樹,向樹里面插入節(jié)點(diǎn)利凑,如果該節(jié)點(diǎn)已存在(節(jié)點(diǎn)值相等),將節(jié)點(diǎn)中的count字段加一嫌术;如果不存在哀澈,將節(jié)點(diǎn)插入樹中,并將節(jié)點(diǎn)的count值置為1度气。自行設(shè)計(jì)數(shù)據(jù)結(jié)構(gòu)割按,插入算法并且分析算法的復(fù)雜度
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);
}
}
}
}
假設(shè)樹中有N個(gè)節(jié)點(diǎn),最多遍歷樹的高度磷籍。時(shí)間復(fù)雜度O(logN)