Java创建和打印特殊数据结构的函数

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);
    }
    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值