标签:图片 null div color vat oid this val mic
1.二叉树的前序遍历:输出当前结点的值之后再去判断是否含有子节点如果有就继续调用递归;
2.二叉树的中序遍历:先判断当前节点的一个子节点是否存在并递归之后再去输出当前节点的值,再继续判断另一边的节点;
3.二叉树的后序遍历:先判断左右两边的子节点是否存在,如果存在就去递归,直到最后的递归完成后再输出当前节点的值
package study03; public class TestBinaryTree { public static void main(String[] args) { //创建父节点 BinaryTree root = new BinaryTree(1); BinaryTree tree2 = new BinaryTree(2); BinaryTree tree3 = new BinaryTree(3); //设置子节点的孩子节点 root.setLeft(tree2); root.setRight(tree3); tree2.setLeft(new BinaryTree(4)); tree2.setRight(new BinaryTree(5)); tree3.setLeft(new BinaryTree(6)); tree3.setRight(new BinaryTree(7)); //创建测试对象 TestBinaryTree t = new TestBinaryTree(); t.preOrder(root);//调用前序遍历 System.out.println("-------------"); t.inOrder(root);//调用中序遍历 System.out.println("-------------"); t.lastOrder(root);//调用后序遍历 } //前序遍历,其实每个遍历就只是输出的位置不一样 private void preOrder(BinaryTree tree){ System.out.print(tree.getValue()+" "); if (tree.getLeft()!=null){ preOrder(tree.getLeft()); } if (tree.getRight()!=null){ preOrder(tree.getRight()); } } //中序遍历 private void inOrder(BinaryTree tree){ if (tree.getLeft()!=null){ inOrder(tree.getLeft()); } System.out.print(tree.getValue()+" "); if (tree.getRight()!=null){ inOrder(tree.getRight()); } } //后序遍历 private void lastOrder(BinaryTree tree){ if (tree.getLeft()!=null){ lastOrder(tree.getLeft()); } if (tree.getRight()!=null){ lastOrder(tree.getRight()); } System.out.print(tree.getValue()+" "); } }
二叉树类:
package study03; public class BinaryTree { private BinaryTree left;//存储左孩子节点的引用 private BinaryTree right;//存储右孩子节点的引用 private int value;//存储本身节点的值 public BinaryTree(int value) { this.value = value; } public BinaryTree getLeft() { return left; } public void setLeft(BinaryTree left) { this.left = left; } public BinaryTree getRight() { return right; } public void setRight(BinaryTree right) { this.right = right; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } }
标签:图片 null div color vat oid this val mic
原文地址:https://www.cnblogs.com/wenrou-pan/p/14526512.html