Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree

 

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

这道题我开始超时了,后面想了个投机取巧的办法。想转换成数组,然后使用上面一道题的方法

  1 /**
  2  * Definition for singly-linked list.
  3  * public class ListNode {
  4  *     int val;
  5  *     ListNode next;
  6  *     ListNode(int x) { val = x; next = null; }
  7  * }
  8  */
  9 /**
 10  * Definition for binary tree
 11  * public class TreeNode {
 12  *     int val;
 13  *     TreeNode left;
 14  *     TreeNode right;
 15  *     TreeNode(int x) { val = x; }
 16  * }
 17  */
 18 public class Solution {
 19     public TreeNode root ;
 20     public int nums[];
 21     
 22     public TreeNode sortedListToBST(ListNode head) {       
 23         ListNode temp = head;
 24         int length = 0;
 25         while(temp != null){
 26             length ++;
 27             temp = temp.next;                    
 28         }
 29         nums = new int[length];
 30         temp = head;
 31         for(int i = 0; i < nums.length; i++){
 32             nums[i] = temp.val;
 33             temp = temp.next;
 34         }
 35         return sortedArrayToBST(nums);
 36     }
 37 
 38     public TreeNode sortedArrayToBST(int[] num) {
 39         if(num.length == 0)
 40             return root;
 41         if(1 == num.length){
 42             return new TreeNode(num[0]);
 43         }
 44         int middle = num.length / 2;
 45         root = new TreeNode(num[middle]);
 46         
 47         createBST(num, 0, middle - 1);
 48         createBST(num, middle + 1, num.length - 1);
 49         return root;
 50     }
 51     
 52     /**
 53      * 根据num数组,创建一棵二叉查找树
 54      * @param num
 55      * @param start
 56      * @param end
 57      */
 58     private void createBST(int num[], int start, int end){
 59         int middle = 0;
 60         if(start <= end && start >= 0 && end <num.length){
 61             middle = (start + end) / 2;
 62             
 63             insertNode(root, num[middle]);
 64             
 65             createBST(num, start, middle - 1);
 66             createBST(num, middle + 1, end);
 67         }
 68     }
 69     
 70     /**
 71      * 向root所指的BST二叉查找树中插入value
 72      * @param root
 73      * @param value
 74      */
 75     private void insertNode(TreeNode root, int value){        
 76         if(value > root.val){                    //比根节点大,在右子树插入
 77             if(root.right == null){
 78                 root.right = new TreeNode(value);
 79             }else{
 80                 root = root.right;
 81                 insertNode(root, value);
 82             }
 83         }
 84         else{
 85             if(root.left == null){
 86                 root.left = new TreeNode(value);
 87             }else{
 88                 root = root.left;
 89                 insertNode(root, value);            //比根节点小的插入左子树
 90             }
 91         }
 92     }
 93     
 94     /**
 95      * 先序遍历
 96      * @param root
 97      */
 98     public void preTravel(TreeNode root){
 99         if(root != null){
100 //            System.out.print(root.val + " ");
101             preTravel(root.left);
102             preTravel(root.right);
103         }
104     }
105 }

 

转载于:https://www.cnblogs.com/luckygxf/p/4189763.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
提供的源码资源涵盖了小程序应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
【Solution】 To convert a binary search tree into a sorted circular doubly linked list, we can use the following steps: 1. Inorder traversal of the binary search tree to get the elements in sorted order. 2. Create a doubly linked list and add the elements from the inorder traversal to it. 3. Make the list circular by connecting the head and tail nodes. 4. Return the head node of the circular doubly linked list. Here's the Python code for the solution: ``` class Node: def __init__(self, val): self.val = val self.prev = None self.next = None def tree_to_doubly_list(root): if not root: return None stack = [] cur = root head = None prev = None while cur or stack: while cur: stack.append(cur) cur = cur.left cur = stack.pop() if not head: head = cur if prev: prev.right = cur cur.left = prev prev = cur cur = cur.right head.left = prev prev.right = head return head ``` To verify the accuracy of the code, we can use the following test cases: ``` # Test case 1 # Input: [4,2,5,1,3] # Output: # Binary search tree: # 4 # / \ # 2 5 # / \ # 1 3 # Doubly linked list: 1 <-> 2 <-> 3 <-> 4 <-> 5 # Doubly linked list in reverse order: 5 <-> 4 <-> 3 <-> 2 <-> 1 root = Node(4) root.left = Node(2) root.right = Node(5) root.left.left = Node(1) root.left.right = Node(3) head = tree_to_doubly_list(root) print("Binary search tree:") print_tree(root) print("Doubly linked list:") print_list(head) print("Doubly linked list in reverse order:") print_list_reverse(head) # Test case 2 # Input: [2,1,3] # Output: # Binary search tree: # 2 # / \ # 1 3 # Doubly linked list: 1 <-> 2 <-> 3 # Doubly linked list in reverse order: 3 <-> 2 <-> 1 root = Node(2) root.left = Node(1) root.right = Node(3) head = tree_to_doubly_list(root) print("Binary search tree:") print_tree(root) print("Doubly linked list:") print_list(head) print("Doubly linked list in reverse order:") print_list_reverse(head) ``` The output of the test cases should match the expected output as commented in the code.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值