二叉搜索树与双向链表
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路
- 按中序遍历二叉搜索树可从小到大遍历元素
- 边遍历元素边创建双向链表
- 最后得到的双向链表的指针指向最后一个节点,所以需要再往回遍历一遍让指针指到头结点
代码
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
TreeNode listNode = null;
listNode = myConvert(pRootOfTree, listNode);
TreeNode listHead = listNode;
while (listHead != null && listHead.left != null) {
listHead = listHead.left;
}
return listHead;
}
public TreeNode myConvert(TreeNode node, TreeNode listNode) {
if (node == null) {
return null;
}
TreeNode current = node;
if (current.left != null) {
listNode = myConvert(current.left, listNode);
}
current.left = listNode;
if (listNode != null) {
listNode.right = current;
}
listNode = current;
if (current.right != null) {
listNode = myConvert(current.right, listNode);
}
return listNode;
}
}
时间: 2024-12-24 23:48:31