代码实现(细节)
public static class Node {
public char val;
//public int val;
public Node left = null;
public Node right = null;
private Node(char val) {
this.val = val;
}
@Override
public String toString() {
return String.format("{%c}", val);
}
}
1.前序遍历递归实现
public static void preOrderTraversal(Node root) {
// 如何找终止条件,肯定是在形参中
if (root == null) {
return;
}
// 根 + 左子树的前序遍历 + 右子树的前序遍历
System.out.println(root);
preOrderTraversal(root.left);
preOrderTraversal(root.right);
}
2.中序遍历递归实现
方法1:
public static void inOrderTraversal(Node root) {
if (root == null) {
return;
}
// 左子树的中序遍历 + 根 + 右子树的中序遍历
inOrderTraversal(root.left);
System.out.println(root);
inOrderTraversal(root.right);
}
方法2:(链表实现)
private static List<Character> inorderList = new ArrayList<>();
private static void inorderReturnList(Node root) {
if (root != null) {
inorderReturnList(root.left);
inorderList.add(root.val);
inorderReturnList(root.right);
}
}
方法3:(链表实现)
private static List<Character