数据结构---9.28----树的遍历

129 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

关于树的遍历,常规的就是前序遍历、中序遍历、后序遍历

在此之前需要一个树的基础结构

树的基础结构

private static class TreeNode {
int data;
TreeNode leftChild;
TreeNode rightChild;
public TreeNode(int data){
this.data = data;
}

}

创建树

  • 利用数组或者列表,模拟装载数据,弹出头部数据作为树顶,利用递归实现左子树和右子树的填充。
public static TreeNode createBinaryTree(LinkedList<Integer> inputList){
    TreeNode node = null;
    if(inputList==null || inputList.isEmpty()){
        return null;
    }
    Integer data = inputList.removeFirst();
    if(data != null){
        node = new TreeNode(data);
        node.leftChild = createBinaryTree(inputList);
        node.rightChild = createBinaryTree(inputList);
    }
    return node;
}

中序遍历

  • 中序遍历:顶、左、右;先判断当前的树是否为空直接取出当前的首位数据作为顶;利用递归实现左子树、右子树;
/**
*二叉树中序遍历
*/
public static void midTravel(TreeNode node){
    if(node == null){
        return;
    }
    System.out.println(node.data);
    midTravel(node.leftChild);
    midTravel(node.rightChild);
}

前序遍历

  • 前序遍历:左、顶、右;先判断当前的树是否为空,递归左子树后直接取出当前的首位数据作为顶;递归右子树;
/**
*二叉树前序遍历
*/
public static void frontTravel(TreeNode node){
    if(node == null){
        return;
    }
    midTravel(node.leftChild);
    System.out.println(node.data);
    
    midTravel(node.rightChild);
}

后序遍历

  • 后序遍历:左、右。顶;先判断当前的树是否为空;利用递归实现左子树、右子树的遍历;直接取出当前的首位数据作为顶;
/**
*二叉树后序遍历
*/
public static void postTravel(TreeNode node){
    if(node == null){
        return;
    }
    midTravel(node.leftChild);
    midTravel(node.rightChild);
    System.out.println(node.data);
}

一般来说,树的遍历都离不开前序后序中序;略微实践并通过变形,才是掌握。