💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 节点 ```java /** * @author virus * @date 2020/11/30 */ public class Node { private int data; private Node leftNode; private Node rightNode; public Node(int data, Node leftNode, Node rightNode) { this.data = data; this.leftNode = leftNode; this.rightNode = rightNode; } public int getData() { return data; } public void setData(int data) { this.data = data; } public Node getLeftNode() { return leftNode; } public void setLeftNode(Node leftNode) { this.leftNode = leftNode; } public Node getRightNode() { return rightNode; } public void setRightNode(Node rightNode) { this.rightNode = rightNode; } } ``` ## 递归遍历 ```java /** * @author virus * @date 2020/11/30 */ public class BinaryTree { private Node init() { Node J = new Node(8, null, null); Node H = new Node(4, null, null); Node G = new Node(2, null, null); Node F = new Node(7, null, J); Node E = new Node(5, H, null); Node D = new Node(1, null, G); Node C = new Node(9, F, null); Node B = new Node(3, D, E); Node A = new Node(6, B, C); // 返回根节点 return A; } private void printNode(Node node) { System.out.print(node.getData()); } /** * 先(根)序遍历(根左右) * * @param root */ private void theFirstTraversal(Node root) { printNode(root); // 使用递归进行遍历左孩子 if (root.getLeftNode() != null) { theFirstTraversal(root.getLeftNode()); } // 递归遍历右孩子 if (root.getRightNode() != null) { theFirstTraversal(root.getRightNode()); } } /** * 中(根)序遍历(左根右) * * @param root */ private void theInOrderTraversal(Node root) { //中序遍历 if (root.getLeftNode() != null) { theInOrderTraversal(root.getLeftNode()); } printNode(root); if (root.getRightNode() != null) { theInOrderTraversal(root.getRightNode()); } } /** * 后(根)序遍历(左右根) * * @param root */ private void thePostOrderTraversal(Node root) { //后序遍历 if (root.getLeftNode() != null) { thePostOrderTraversal(root.getLeftNode()); } if (root.getRightNode() != null) { thePostOrderTraversal(root.getRightNode()); } printNode(root); } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); Node root = tree.init(); System.out.println("先序遍历"); tree.theFirstTraversal(root); System.out.println(""); System.out.println("中序遍历"); tree.theInOrderTraversal(root); System.out.println(""); System.out.println("后序遍历"); tree.thePostOrderTraversal(root); System.out.println(""); } } ```