将二叉查找树转换成双链表
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将二叉查找树转换成双链表相关的知识,希望对你有一定的参考价值。
将一个二叉查找树按照中序遍历转换成双向链表
样例
给定一个二叉查找树:
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); } };
以上是关于将二叉查找树转换成双链表的主要内容,如果未能解决你的问题,请参考以下文章