编程题-有序链表转换二叉搜索树

https://blog.youkuaiyun.com/qq_38386316/article/details/83033169

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

思路:中间的作为根节点进行构造,找链表的中间节点依旧可以使用快慢指针的方法进行找。

实例 :给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

参考 https://blog.youkuaiyun.com/qq_38386316/article/details/83033169 包含main方法 

 public static ListNode stringToListNode(String input) {
        int[] nodes = stringToArrays(input);
        ListNode dummpy = new ListNode(-1);
        ListNode cur = dummpy;
        for(int x : nodes) {
            cur.next = new ListNode(x);
            cur = cur.next;
        }
        return dummpy.next;
    }
public static String treeNodeToString(TreeNode root) {
        if(root == null) {
            return "[]";
        }
        String ouput = "";
        Queue<TreeNode> nodeQueue = new LinkedList<>();
        nodeQueue.add(root);
        while(!nodeQueue.isEmpty()) {
            TreeNode node = nodeQueue.remove();
            if(node == null) {
                ouput += "null, ";
                continue;
            }
            ouput += String.valueOf(node.val) + ", ";
            nodeQueue.add(node.left);
            nodeQueue.add(node.right);
        }
        return "[" + ouput.substring(0, ouput.length() - 2) + "]";
    }
 

剑指offer36题  二叉搜索树和双向链表

思路: 在二叉搜索树中,左子结点的值总是小于父结点的值,右子结点的值总是大于父结点的值。因此在转换成排序双向链表时,原先指向左子结点的指针调整为链表中指向前一个结点的指针,原先指向右子结点的指针调整为链表中指向后一个结点的指针。

改变原来指向左子节点和右子节点的指针,让他们分别指向前节点和后节点即可,原先指向左子节点的指针调整为链表中指向前一个节点的指针  原先指向右子节点的指针调整为链表中指向后一个节点的指针

按照中序递归遍历中,当我们遍历转换到根结点时,它的左子树已经转换成了一个排序的链表,并且此时链表尾部的值为左子树中最大结点。我们将它和根结点链接起来,此时根结点变成了链表尾部,接着去遍历右子树,我们知道中序遍历根结点后的一个结点此时为右子树最小结点,我们将它和根结点链接起来。左右子树再用这样的办法,即递归即可解决问题。
 

public static BinaryTreeNode baseconvert(BinaryTreeNode root, BinaryTreeNode lastNode) {

if (root == null)

return lastNode;

BinaryTreeNode current = root;

if (current.leftNode != null)

lastNode=baseconvert(current.leftNode, lastNode);

current.leftNode = lastNode;

if (lastNode != null)

lastNode.rightNode = current;

lastNode = current;

if (current.rightNode != null)

lastNode=baseconvert(current.rightNode, lastNode);

return lastNode;

}

转自 https://www.cnblogs.com/keedor/p/4467040.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值