二叉树创建与遍历(LinkedList+递归思想)

    xiaoxiao2021-04-15  364

    自定义的节点类,TreeNode:

    package chapter3; public class TreeNode { int data; TreeNode leftNode; TreeNode rightNode; public TreeNode(int data) { this.data = data; } }

     

    package chapter3; import java.util.Arrays; import java.util.LinkedList; import org.junit.Test; public class BinaryTreePrint { @Test public void printBinaryTree(){ LinkedList<Integer> inputList = new LinkedList<Integer>(Arrays. asList(new Integer[] {3,2,9,null,null,10,null,null,8,null,4})); TreeNode treeNode = createBinaryTree(inputList); System.out.println("前序输出:"); preOutPrint(treeNode); System.out.println("中序输出:"); minOutPrint(treeNode); System.out.println("后序输出:"); lastOutPrint(treeNode); } private void lastOutPrint(TreeNode node) { if(node == null) { return; } lastOutPrint(node.leftNode); lastOutPrint(node.rightNode); System.out.println(node.data); } private void minOutPrint(TreeNode node) { if(node == null) { return; } minOutPrint(node.leftNode); System.out.println(node.data); minOutPrint(node.rightNode); } private void preOutPrint(TreeNode node) { if(node == null) { return; } System.out.println(node.data); preOutPrint(node.leftNode); preOutPrint(node.rightNode); } private TreeNode createBinaryTree(LinkedList<Integer> inputList) { TreeNode node = null; if(inputList == null || inputList.isEmpty()) {//LinkedList判空方法 return null; } Integer data = inputList.removeFirst();//不使用int,JDK自带的LinkedList的removeFirst()方法,获取并返回第1个元素 if(data != null) { node = new TreeNode(data); node.leftNode = createBinaryTree(inputList); node.rightNode = createBinaryTree(inputList); } return node;//控制null,控制头结点(返回根),控制出口 } }

    参考:程序员小灰

     

     


    最新回复(0)