标签:二叉树
class BinaryTree { treenode head; class treenode { private int val; public treenode left; public treenode right; public treenode(int val) { this.val=val; left=null; right=null; } } public void add(int n) //构造树或插入值 { treenode node=new treenode(n); if(isempty()) head=node; else insert(node); } private void insert(treenode node) //向树中插入值 { treenode cur=head; while(cur!=null) { if(node.val<=cur.val) { if(cur.left==null) cur.left=node; cur=cur.left; } else if(node.right==null) cur.right=node; cur=cur.right; } } public void delete(int n) { } public treenode find(int n) //找到n所在的节点 { treenode tmp=head; while(tmp!=null) { if(tmp.val>n) tmp=tmp.left; else if(tmp.val<n) tmp=tmp.right; else return tmp; } return null; } public boolean isleaf(int n) //是否为空树 { treenode tmp=find(n); if(tmp!=null&&tmp!=head&&tmp.left==null&&tmp.right==null) return true; return false; } public treenode parent(int n) //父节点 { LinkenList<treenode> l=new LinkenList<treenode>(); treenode cur; treenode node=find(n); l.offer(head); while(l.size()>0) { cur=l.poll(); if(cur.left==node||cur.right==node) return cur; if(cur.left!=null) l.offer(cur.left) if(cur.right!=null l.offer(cur.right) } return null; } public int max(treenode node) //最大节点值 { treenode tmp=node; if(tmp==null) return -1; while(tmp!=null) tmp=tmp.right; return tmp.val; } public int min(treenode node) //最小节点值 { treenode tmp=node; if(tmp==null) return -1; while(tmp!=null) tmp=tmp.left; return tmp.val; } public void deleteleaf(int n) //删除叶子节点 { treenode node=find(n); treenode parent=parent(n); if(parent.left==node) parent.left==null; else parent.right==null; } }
标签:二叉树
原文地址:http://zhenzhuangde.blog.51cto.com/10697385/1734268