Lintcode 将二叉查找树转换成双链表

/**
 * 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)//@return: the head of doubly list node
	{
		if(root == NULL)
		return NULL;
		//DoublyListNode* headnode;
		
		DoublyListNode* droot = new DoublyListNode(NULL); 这个地方一定要注意 初始化!!!!!!!!!!!!!,如果不初始化相当于一个野指针
		droot->val = root->val;
		
		if(root->left != NULL)
		{
			DoublyListNode* head , *p ;
			head = bstToDoublyList(root->left);
			p = head;
			while(p->next != NULL)
				p = p->next;
			p->next = droot; droot->prev = p;
			if(root->right != NULL)
			{
				DoublyListNode* r = bstToDoublyList(root->right);
				droot->next = r;
				r->prev = droot;
				
			}
			return head;
		}
		else
		{
			
			if(root->right != NULL)
			{
				DoublyListNode* r = bstToDoublyList(root->right);
				droot->next = r;
				r->prev = droot;
				
			}
			return droot;
		}
	}
};


将一个二叉查找树按照中序遍历转换成双向链表。

您在真实的面试中是否遇到过这个题?
  Yes
样例

给定一个二叉查找树:

    4
   / \
  2   5
 / \
1   3

返回 1<->2<->3<->4<->5

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/u010864884/article/details/49373819
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞