LeetCode 109. 有序链表转换二叉搜索树

it2025-03-01  22

思路:

快慢指针找到中间节点,中间节点为根节点,

将链表分为左右两部分(注意前半部分节点next置null),左部分为左子树,右部分为右子树

递归实现左右子树,返回根节点

public static TreeNode sortedListToBST(ListNode head) { if(head == null)return null; else if(head.next==null)return new TreeNode(head.val); ListNode slow = head; ListNode p = slow.next; ListNode fast = p.next; while (fast!=null && fast.next!=null){ slow=slow.next; p=slow.next; fast = fast.next.next; } slow.next = null; TreeNode root = new TreeNode(p.val); root.left = sortedListToBST(head); root.right = sortedListToBST(p.next); return root; }

 

 

 

最新回复(0)