java使用归并删除法删除二叉树中节点的方法
更新时间:2015年05月30日 15:57:34 作者:hitxueliang
这篇文章主要介绍了java使用归并删除法删除二叉树中节点的方法,实例分析了java二叉树算法的相关操作技巧,需要的朋友可以参考下
本文实例讲述了java使用归并删除法删除二叉树中节点的方法。分享给大家供大家参考。具体分析如下:
实现的思想很简单:
first:找到要删除的节点
second:如果删除的节点没有右子树那么左子树链到父节点
third:如果删除的节点没有左子树那么右子树链到父节点
forth:如果删除的节点又左右孩子,那么可以归并删除节点后的子树:方法有两种一种是用删除节点的左子树的最右节点,指向删除节点的右子树,另一种是用删除节点的用字数的最左节点指向删除节点的左子树。
Java 实现如下:
public void deleteByMerging(int el) { IntBSTNode tmp,node,p=root,prev=null; /*find the node to be deleted*/ while(p!=null&&p.key!=el) { prev=p; if(p.key<el) p=p.right; else p=p.left; } /*find end*/ node=p; if(p!=null&&p.key==el) { if(node.right==null) //node has no right child then its left child (if any) is attached to node=node.left; //its parent else if(node.left==null) //node has no left child then its right child (if any) is attched to node=node.right //its parent else{ tmp=node.left; while(tmp.right!=null) tmp=tmp.right; //find the rightmost node of the left subtree tem.right=node.right; //establish the link between the rightmost node of the left subtree and the right subtree node=node.left; } if(p==root) { root=node; } else if (prev.left==p) { prev.left=node; } else prev.right=node } else if(root!=null) { System.out.println("the node is not in the tree"); } else System.out.println("The tree is empty"); }
希望本文所述对大家的java程序设计有所帮助。
相关文章
Spring Boot 基于注解的 Redis 缓存使用详解
本篇文章主要介绍了Spring Boot 基于注解的 Redis 缓存使用详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-05-05springboot结合mybatis-plus快速生成项目模板的方法
Mybatis-Plus是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生,接下来通过本文给大家分享springboot结合mybatis-plus快速生成项目模板的方法,感兴趣的朋友一起看看吧2021-06-06
最新评论