请先关注 [低调大师] 公众号 优秀的自媒体个人博客,低调大师,许军

低调大师

您现在的位置是:首页>文章详情

文章详情

算法:二叉树代码示例

2019-08-05 33热度

二叉树特点

左节点值小于根节点值,右节点值大于根节点

 public class BinaryTree { private Node root; @Data private static class Node { private int data; private Node left; private Node right; public Node(int data){ this.data = data; } } public Node find(int key){ Node current = root; while(current != null){ if(current.data > key){ current = current.left; } if(current.data < key){ current = current.right; } if(current.data == key){ return current; } } return null; } public boolean insert(int data){ Node newNode = new Node(data); if(root == null){ root = newNode; return true; }else{ Node current = root; Node parent = null; while (current != null){ parent = current; if(current.data > data){ current = current.left; if(current == null){ parent.left = newNode; return true; } } else{ current = current.right; if(current == null){ parent.right = newNode; return true; } } } } return false; } public Node findMax(){ Node current = root; while(current != null){ current = current.right; } return current; } public Node findMin(){ Node current = root; while (current != null) { current = current.left; } return current; } //删除没有子节点的节点 public boolean delete(int key){ Node current = root; Node parent = current; boolean isLeft = false; while (current.data != key){ parent = current; if(current.data > key){ isLeft = true; current = current.left; }else { isLeft = false; current = current.right; } if(current == null){ return false; } } if(current.left == null && current.right == null){ if(current == root){ root = null; } if(isLeft){ parent.left = null; }else{ parent.right = null; } return true; } return false; } }
收藏 (0)

相关文章

    文章评论

    共有0条评论来说两句吧...