输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表

本文介绍了一种算法,将二叉搜索树转换为排序的双向链表,通过调整树中节点指针指向,不创建新节点。示例代码展示了如何实现此转换,并遍历输出链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表

要求不能创建人和新的结点,只能调整树中结点指针的指向

 

解答:

 1 public class Solution {
 2     public static void main(String[] args) {
 3         BinaryTreeNode root=new BinaryTreeNode(10);
 4         BinaryTreeNode node1=new BinaryTreeNode(6);
 5         BinaryTreeNode node2=new BinaryTreeNode(14);
 6         BinaryTreeNode node3=new BinaryTreeNode(4);
 7         BinaryTreeNode node4=new BinaryTreeNode(8);
 8         BinaryTreeNode node5=new BinaryTreeNode(12);
 9         BinaryTreeNode node6=new BinaryTreeNode(16);
10         root.setLchildNode(node1);root.setRchildNode(node2);
11         node1.setLchildNode(node3);node1.setRchildNode(node4);
12         node2.setLchildNode(node5);node2.setRchildNode(node6);
13         BinaryTreeNode head=covert(root);
14 
15         while(head != null) {
16             System.out.println(head.getData());
17             head = head.getRchildNode();
18         }
19     }
20 
21     private static BinaryTreeNode covert(BinaryTreeNode root) {
22         BinaryTreeNode lastNodeList = null;
23         lastNodeList = covertNode(root, lastNodeList);
24 
25         while(lastNodeList != null && lastNodeList.getLchildNode() != null) {
26             lastNodeList = lastNodeList.getLchildNode();
27         }
28 
29         return lastNodeList;
30     }
31 
32     private static BinaryTreeNode convertNode(BinaryTreeNode root, BinaryTreeNode lastNodeList) {
33         if(root == null) {
34             return null;
35         }
36 
37         BinaryTreeNode current = root;
38         if(current.getLchildNode() != null) {
39             lastNodeList = covertNode(current.getLchildNode(), lastNodeList);
40         }
41 
42         current.setLchildNode(lastNodeList);
43 
44         if(lastNodeList != null) {
45             lastNodeList.setRchildNode(current);
46         }
47 
48         lastNodeList = current;
49 
50         if(current.getRchildNode() != null) {
51             lastNodeList = covertNode(current.getRchildNode(), lastNodeList);
52         }
53 
54         return lastNodeList;
55     }
56 
57 
58 }

 

转载于:https://www.cnblogs.com/wylwyl/p/10369488.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值