Lintcode 将二叉查找树转换为双链表
来源:互联网 发布:树莓派ubuntu系统 编辑:程序博客网 时间:2024/06/09 21:02
将二叉查找树转换成双链表
描述
笔记
数据
评测
将一个二叉查找树按照中序遍历转换成双向链表。
您在真实的面试中是否遇到过这个题? 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; }};
上面的程序中,会出现指针(引用)传递的现象(其实我也不知道指针传递和引用传递有啥区别,感觉都是传递了指针啊),我觉得下次遇见这种需要传递指针的情况可以定义全局变量,这样就不会随着函数调用其结束而清除数据了。
0 0
- Lintcode 将二叉查找树转换为双链表
- Lintcode 将二叉查找树转换成双链表
- lintcode,将二叉查找树转换成双链表
- [LintCode]378.将二叉查找树转换成双链表
- 将二叉查找树转换成双链表-LintCode
- 将二叉查找树转换为有序双链表
- 将二叉查找树转换为其镜像
- LintCode-剑指Offer-(378)将二叉查找树转换成双链表
- LintCode将二叉查找树转换成双链表JAVA版
- [LintCode] 将二叉查找树转换成双链表 Convert Binary Search Tree to Doubly Linked List
- LintCode-排序列表转换为二分查找树
- lintcode-排序列表转换为二分查找树-106
- LintCode:排序列表转换为二分查找树
- lintcode,排序列表转换为二分查找树
- LintCode 106-排序列表转换为二分查找树
- lintcode 排序列表转换为二分查找树(
- LintCode 排序列表转换为二分查找树
- 排序列表转换为二分查找树-LintCode
- Overload(重载)Override(重写)
- OpenCV学习笔记(二)—— OpenCV整体结构
- Caffe学习系列(3):视觉层(Vision Layers)及参数
- 数组指针的声明和引用
- 笔试面试学习之路(二)
- Lintcode 将二叉查找树转换为双链表
- easyUI设置下拉列表默认值
- EXTJS4.2中单选框及多选框
- 使用Hbuilder和MUI开发Hybird app笔记
- 内存映射机制
- xml基本知识详解
- 在工程里寻找各种对象(如:右键菜单pop1,在menus里面寻找)
- iOS-UITableView侧滑多个按钮
- R语言︱排序问题