二叉树的遍历

下面上代码,用链表实现二叉树:

public class BinaryTreeData {
  private String value;
  private BinaryTreeData leftChild;
  private BinaryTreeData rightChild;

  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  public BinaryTreeData getLeftChild() {
    return leftChild;
  }

  public void setLeftChild(BinaryTreeData leftChild) {
    this.leftChild = leftChild;
  }

  public BinaryTreeData getRightChild() {
    return rightChild;
  }

  public void setRightChild(BinaryTreeData rightChild) {
    this.rightChild = rightChild;
  }
}

 

二叉树的遍历从方法上可以分为:深度优先遍历、广度优先遍历;这一点和图很像,因为树就是图的字类嘛。

广度遍历,就是按层级遍历,即从上到下,一层一层遍历,代码:

  public static void printTreeByBreath(BinaryTreeData binaryTreeData) {
    if (binaryTreeData == null || StringUtils.isBlank(binaryTreeData.getValue())) {
      return;
    }
    Queue<BinaryTreeData> treeDataQueue = new LinkedList<>();
    treeDataQueue.offer(binaryTreeData);
    while (!treeDataQueue.isEmpty()){
      BinaryTreeData pollNode = treeDataQueue.poll();
      System.out.println(pollNode.getValue());
      if(pollNode.getLeftChild()!=null){
        treeDataQueue.offer(pollNode.getLeftChild());
      }
      if(pollNode.getRightChild()!=null){
        treeDataQueue.offer(pollNode.getRightChild());
      }
    }
  }

 

深度遍历,从顺序上又分为:前序遍历、中序遍历、后序遍历:

 

前序遍历:

  public static void printTree(BinaryTreeData binaryTreeData) {
    if (binaryTreeData == null || StringUtils.isBlank(binaryTreeData.getValue())) {
      return;
    }

    //前序遍历
    System.out.println(binaryTreeData.getValue());
    printTree(binaryTreeData.getLeftChild());
    printTree(binaryTreeData.getRightChild());

  }

 

中序遍历:

  public static void printTree(BinaryTreeData binaryTreeData) {
    if (binaryTreeData == null || StringUtils.isBlank(binaryTreeData.getValue())) {
      return;
    }

    //中序遍历
    printTree(binaryTreeData.getLeftChild());
    System.out.println(binaryTreeData.getValue());
    printTree(binaryTreeData.getRightChild());

  }

 

后序遍历:

  public static void printTree(BinaryTreeData binaryTreeData) {
    if (binaryTreeData == null || StringUtils.isBlank(binaryTreeData.getValue())) {
      return;
    }

    //后序遍历
    printTree(binaryTreeData.getLeftChild());
    printTree(binaryTreeData.getRightChild());
    System.out.println(binaryTreeData.getValue());

  }

 

posted @ 2021-12-28 11:04  hucat  阅读(31)  评论(0)    收藏  举报