From f7a21e419cace3de43e9f0d0dd564cf1a06cc623 Mon Sep 17 00:00:00 2001 From: Kai Jiang Date: Mon, 27 Nov 2017 11:21:18 -0800 Subject: [PATCH] Update convert-binary-search-tree-to-doubly-linked-list.cpp --- ...nary-search-tree-to-doubly-linked-list.cpp | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/C++/convert-binary-search-tree-to-doubly-linked-list.cpp b/C++/convert-binary-search-tree-to-doubly-linked-list.cpp index 3ace3db..d379c3e 100644 --- a/C++/convert-binary-search-tree-to-doubly-linked-list.cpp +++ b/C++/convert-binary-search-tree-to-doubly-linked-list.cpp @@ -51,3 +51,37 @@ class Solution { treeToDoublyList(p->right, prev, head); } }; + + + + +// A simple recursive function to convert a given Binary tree to Doubly +// Linked List +// root --> Root of Binary Tree +// head --> Pointer to head node of created doubly linked list +void BinaryTree2DoubleLinkedList(node *root, node **head) +{ + // Base case + if (root == NULL) return; + + // Initialize previously visited node as NULL. This is + // static so that the same value is accessible in all recursive + // calls + static node* prev = NULL; + + // Recursively convert left subtree + BinaryTree2DoubleLinkedList(root->left, head); + + // Now convert this node + if (prev == NULL) + *head = root; + else + { + root->left = prev; + prev->right = root; + } + prev = root; + + // Finally convert right subtree + BinaryTree2DoubleLinkedList(root->right, head); +}