二叉树是每个节点最多有两个子树的树结构。它有五种基本形态:二叉树可以是空集;根可以有空的左子树或右子树;或者左、右子树皆为空。
2^{i-1}
(i≥1)。叶节点
只能出现在最下层和次下层,并且最下面一层的结点都集中在该层最左边的若干位置的二叉树12345678910111213141516171819202122232425262728293031323334353637383940414243 | /** * 插入节点 * @param value 节点的值 */ public void insertNode(int value){ //如果根节点为null if (root==null) { root=new Node(value,null,null); //创建根节点,此时没有左右子节点 return; //返回即可,表示插入成功,这个插入的节点就是根节点 } //如果根节点已经存在,那么就需要从根节点开始比较大小 Node currentNode=root; //当前节点 Node parentNode=root; //当前节点的父节点,需要保存这个节点 boolean isLeftChild=true; //记录待插入的数是parentNode的左节点还是右节点 //当当前节点不为空,表示没有找到插入的位置,当currentNode节点为null的时候,那么这个就是待插入的位置 while(currentNode!=null){ parentNode=currentNode; //保存当前节点的父节点 //如果待插入的值小于当前值,那么到当前节点的左子树中查找 if (value<currentNode.getValue()) { currentNode=currentNode.getLeftChild(); //当前节点继续向下成为左子节点 isLeftChild=true; //左节点 }else if (value>currentNode.getValue()) { //如果待插入的数大于当前节点的值,那么到当前节点的右边查找 currentNode=currentNode.getRightNode(); isLeftChild=false; }else { //value和currentNode.value相等,不允许插入 System.out.println(value+"已经存在,不允许插入"); return; //直接返回,后面的数字不用插入了 } } //循环结束,此时的parentNode就是待插入数字的父节点 //如果待插入的节点是左子节点 if (isLeftChild) { Node node=new Node(value, null, null); parentNode.setLeftChild(node); //设置左节点 }else { //是右子节点 Node node=new Node(value, null, null); parentNode.setRightNode(node); //设置右节点 } } |
---|
123456789101112131415161718 | /** * 在二叉查找树中查找指定的值 * @param value * @return 返回的找到的节点,如果为null表示没有找到 * 从根节点查找,比较值,如果大于,在右子树中查找,如果小于在左子树中查找 */public Node findValue(int value){ Node currentNode=this.root; //从根节点开始查找 //如果currentNode不为null并且值不相等,跳出循环的条件是:要么没有找到,返回null,要么找到了,值相等 while(currentNode!=null&¤tNode.value!=value){ if (value<currentNode.getValue()) { currentNode=currentNode.getLeftChild(); }else { currentNode=currentNode.getRightNode(); } } return currentNode;} |
---|
前序遍历
左子树,最后再前面序遍历
右子树,即是: 父节点 – 左 子树 — 右子树123456789101112131415161718 | //前序遍历对外的方法 public void PreOrder(){ PreOrder(this.root); //从根节点开始访问 } /** * 前序遍历 * 递归 * @param node 父节点 */ private void PreOrder(Node node){ //如果节点不为null if (node!=null) { System.out.println(node.getValue()); //输出值 PreOrder(node.getLeftChild()); //访问左子树 PreOrder(node.getRightNode()); //访问右子树 } } |
---|
123456789101112 | //中序遍历对外的方法 public void InOrder(){ InOrder(this.root); //传入根节点 } private void InOrder(Node node){ if (node!=null) { InOrder(node.getLeftChild()); //先遍历左子树 System.out.println(node.getValue()); InOrder(node.getRightNode()); //遍历右子树 } } |
---|
12345678910111213 | //后序遍历对外的方法 public void PostOrder(){ this.PostOrder(this.root); //从根节点开始 } //后序遍历 private void PostOrder(Node node){ if(node!=null){ PostOrder(node.getLeftChild()); //遍历左子树 PostOrder(node.getRightNode()); //遍历右子树 System.out.println(node.getValue()); //输出 } } |
---|