将二叉查找树转换成双链表
描述
笔记
数据
评测
将一个二叉查找树按照中序遍历转换成双向链表。
您在真实的面试中是否遇到过这个题? Yes
样例
给定一个二叉查找树:
4
/ \
2 5
/ \
1 3
返回 1<->2<->3<->4<->5。
想法:没有要求原地拆分二叉树,所以可以在中序遍历的过程中一遍按中序访问节点,一边生成链表节点,最后返回头节点。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Definition of Doubly-ListNode
* class DoublyListNode {
* public:
* int val;
* DoublyListNode *next, *prev;
* DoublyListNode(int val) {
* this->val = val;
this->prev = this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of tree
* @return: the head of doubly list node
*/
DoublyListNode* bstToDoublyList(TreeNode* root) {
// Write your code here
DoublyListNode * head = NULL;
DoublyListNode * pLastInlist = NULL;
return InOrderTree(root,&head,&pLastInlist);//这里head和pLastInlist是要在递归期间传递的,也就是一个函数的调用期结束后还应该继续存在,否则每次都被刷新掉就得不到返回值了。
}
DoublyListNode * InOrderTree(TreeNode * root, DoublyListNode **head,DoublyListNode ** pLastInList){//由于实参是*&类型的,所以声明形参的时候就要声明成**类型。但在函数定义中的函数递归调用时就不用&了,因为本身就是**类型的。
if(root == NULL){
return *head;
}
DoublyListNode * curNode;
if(root->left!=NULL){
InOrderTree(root->left,head,pLastInList);
}
curNode = new DoublyListNode(root->val);
curNode ->prev = *pLastInList;
if(*pLastInList!= NULL){
(*pLastInList) ->next = curNode;
}
if(*pLastInList == NULL){
*head = curNode;
//cout<<"head = "<<(*head)->val<<"curNode ="<<curNode->val<<endl;
}
*pLastInList = curNode;
//cout<<"curNode = "<<curNode->val<<endl;
//cout<<"head = "<<head->val<<endl;
if(root->right != NULL){
InOrderTree(root->right,head,pLastInList);
}
//cout<<"curNode1 = "<<curNode->val<<endl;
//cout<<"head1 = "<<(*head)->val<<endl;
return *head;
}
};
上面的程序中,会出现指针(引用)传递的现象(其实我也不知道指针传递和引用传递有啥区别,感觉都是传递了指针啊),我觉得下次遇见这种需要传递指针的情况可以定义全局变量,这样就不会随着函数调用其结束而清除数据了。