二叉搜索树与双向链表
二叉搜索树与双向链表
http://www.nowcoder.com/questionTerminal/947f6eb80d944a84850b0538bf0ec3a5
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
//1. 深度遍历,按照从右边的子结点、该结点和左边的子结点依次加入栈中
// 这样就可以使得栈弹出的结点是从小到大这样的排列次序
//2. 从栈中依次弹出结点,该结点的左指针指向上一结点,右指针指向下一结点,
// 然后构成双向链表
void dfs(TreeNode* root,stack<TreeNode* > &s)
{
if(root->right!=NULL)
dfs(root->right,s);
s.push(root);
if(root->left!=NULL)
{
dfs(root->left,s);
}
}
TreeNode* Convert(TreeNode* pRootOfTree)
{
//检查是否为空
if(pRootOfTree==NULL)
return NULL;
stack<TreeNode* > s;
dfs(pRootOfTree,s);
//生成一个临时的头结点
TreeNode *head = new TreeNode(-1);
TreeNode *tmp = head;
//从栈中依次弹出结点,该结点的左指针指向上一结点,右指针指向下一结点
while(!s.empty())
{
TreeNode *t = s.top();
tmp->right = t;
t->left = tmp;
tmp = tmp->right;
s.pop();
}
//头结点向右移一个
head = head->right;
//头结点的做指针指向NULL
head->left = NULL;
return head;
}
};
查看12道真题和解析