链表二叉树构造

1、链表构造

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
def listnodeInput(nums):
    dummy = ListNode(0)
    root = ListNode(nums[0])
    dummy.next = root
    i = 1
    while i < len(nums):
        node = ListNode(nums[i])
        root.next = node
        root = node
        i += 1
    return dummy.next       

2、二叉树构造

class TreeNode:
    def __init__(self, val, left = None, right = None):
        self.val = val
        self.left = left
        self.right = right
def treenodeInput(nums, index):
    if index >= len(nums):
        return
    if nums[index] == 0:
        return None
    left = index * 2 + 1
    right = index * 2 + 2
    root = TreeNode(nums[index])
    root.left = treenodeInput(nums, left)
    root.right = treenodeInput(nums, right)
    return root
    
在Java中,可以使用三叉链表构造二叉树。下面是一个示例代码,演示了如何使用三叉链表实现二叉树的基本操作。 ```java // 定义二叉树节点类 class BTNode { int data; BTNode left; BTNode right; BTNode parent; public BTNode(int data) { this.data = data; this.left = null; this.right = null; this.parent = null; } } // 构造二叉树的类 class BinaryTree { BTNode root; public BinaryTree() { this.root = null; } // 插入节点 public void insert(int data) { BTNode newNode = new BTNode(data); if (root == null) { root = newNode; } else { BTNode current = root; BTNode parent; while (true) { parent = current; if (data < current.data) { current = current.left; if (current == null) { parent.left = newNode; newNode.parent = parent; return; } } else { current = current.right; if (current == null) { parent.right = newNode; newNode.parent = parent; return; } } } } } // 其他二叉树操作方法... // 复制二叉树 public void copyTree(BTNode dstTreeRoot, BTNode srcTreeRoot) { if (srcTreeRoot == null) { dstTreeRoot = null; } else { dstTreeRoot = new BTNode(srcTreeRoot.data); if (srcTreeRoot.left != null) { copyTree(dstTreeRoot.left, srcTreeRoot.left); dstTreeRoot.left.parent = dstTreeRoot; } if (srcTreeRoot.right != null) { copyTree(dstTreeRoot.right, srcTreeRoot.right); dstTreeRoot.right.parent = dstTreeRoot; } } } } // 示例代码 public class Main { public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.insert(5); tree.insert(3); tree.insert(7); tree.insert(2); tree.insert(4); tree.insert(6); tree.insert(8); // 复制二叉树 BinaryTree copiedTree = new BinaryTree(); copiedTree.copyTree(copiedTree.root, tree.root); // 其他操作... } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值