【概念】
先序: 根、左、右
中序: 左、根、右
后序: 左、右、根
【代码】
package com.company;
import java.util.*;
import java.util.stream.Collectors;
/**
* 二叉树节点
*/
class TreeNode {
int data;
TreeNode left;
TreeNode right;
TreeNode(int data){
this.data = data;
}
@Override
public String toString() {
return "TreeNode{" +
"data=" + data +
", left=" + left +
", right=" + right +
'}';
}
}
public class threeSum {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>(Arrays.
asList(new Integer[]{3,2,9,null,null,10,null,
null,8,null,4}));
TreeNode treeNode = createBinaryTree(list);
System.out.println(treeNode.toString());
System.out.println("前序:");
preOrderTraveral(treeNode);
System.out.println("\n中序:");
inOrderTraveral(treeNode);
System.out.println("\n后序:");
postOrderTraveral(treeNode);
}
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.left = createBinaryTree(inputList);
node.right = createBinaryTree(inputList);
}
return node;
}
// 先序: 根 左 右
public static void preOrderTraveral(TreeNode node) {
if (node == null) {
return;
}
System.out.print(node.data + " ");
preOrderTraveral(node.left);
preOrderTraveral(node.right);
}
// 中序: 左 根 右
public static void inOrderTraveral(TreeNode node) {
if (node == null) {
return;
}
inOrderTraveral(node.left);
System.out.print(node.data + " ");
inOrderTraveral(node.right);
}
// 后序: 左、右、根
public static void postOrderTraveral(TreeNode node) {
if (node == null) {
return;
}
inOrderTraveral(node.left);
inOrderTraveral(node.right);
System.out.print(node.data + " ");
}
}