1、leetcode 的 ListNode
的数据结构
ListNode
的节点:
/* Definition for singly-linked list. */
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
用于创建建 ListNode
的函数:
public ListNode init(int[] a){
ListNode head = new ListNode(0); // 带头链表头结点
head.next = null;
ListNode node = head;
for (int i = 0; i < a.length; i++) {
// 初始化新节点
ListNode cur = new ListNode(a[i]);
cur.next = null;
node.next = cur; // 指向新创建的节点
node = node.next; // 指针右移
}
return head.next; // 返回无头链表的头节点
}
用于打印 ListNode
的函数:
public static void printListNode(ListNode head){
if (head == null)
return;
ListNode p = head;
while (p != null){
System.out.print(p.val);
System.out.print("->");
p = p.next;
}
System.out.println("NULL");
}
2、TreeNode
二叉树
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int x) { val = x; }
}
先序创建和打印二叉树:
class TreeNodeOp{
static int inputIndex = 0; // 用于记录数组下标,类似于输入顺序
public static TreeNode createTree(TreeNode root ,Integer[] a, int index){
if (index < a.length){
if (a[index] == null) {
root = null;
}else {
root.val = a[index]; // 根节点赋值
root.left = createTree(new TreeNode(), a, ++inputIndex); // 创建左子树
root.right = createTree(new TreeNode(), a, ++inputIndex); // 创建右子树
}
}
return root;
}
public static void printTreeNode(TreeNode root){
if (root != null){
System.out.print(root.val + " "); // 打印节点
printTreeNode(root.left); // 遍历左子树
printTreeNode(root.right); // 遍历右子树
}else {
System.out.print("null "); // 子树为空,输出 null
}
}
public static void main(String[] args) {
Integer[] a = {3, 9, null, null, 20, 15, null, null, 7, null, null}; // 先序遍历数组
TreeNode root = createTree(new TreeNode(), a, 0);
printTreeNode(root);
}
}