首页 > 代码库 > 将二叉查找树转换成双链表
将二叉查找树转换成双链表
将一个二叉查找树按照中序遍历转换成双向链表
样例
给定一个二叉查找树:
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* list = NULL; DoublyListNode* bstToDoublyList(TreeNode* root) { // Write your code here if (root == NULL) return NULL; inorder(root); while (list->prev != NULL) list = list->prev; return list; } void inorder(TreeNode* root) { if (root->left != NULL) inorder(root->left); DoublyListNode* temp = new DoublyListNode(root->val); if (list == NULL) { list = temp; } else if (list != NULL) { list->next = temp; temp->prev = list; list = temp; } if (root->right != NULL) inorder(root->right); } };
将二叉查找树转换成双链表
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。