您的位置:首页 > Web前端

【剑指offer】十八,二叉搜索树与双向链表

2015-09-11 15:38 537 查看

题目描述

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

分析:将二叉搜索树转换成一个排序的双向链表,即在对二叉搜索进行中序遍历时,将节点指向左子树的指针指向中序遍历的前一个节点,将节点指向右子节点的指针指向中序遍历的下一个节点。需要注意的是左子树的最右节点,右子树的最左节点。代码如下:

/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
TreeNode tail  = null ;
public TreeNode Convert(TreeNode pRootOfTree) {
convertNode(pRootOfTree);
TreeNode head = tail ;
while(head!=null&&head.left!=null){
head = head.left;
}
return head ;
}
private void convertNode(TreeNode node) {
if(node==null){
return ;
}
TreeNode current = node ;
if(current.left!=null){
convertNode(current.left);
}
current.left = tail ;
if(tail!=null){
tail.right=current ;
}
tail = current ;
if(current.right!=null){
convertNode(current.right);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: