# "Sword point offer" binary search tree and doubly linked list

Source: Internet
Author: User

Title Description

Enter a binary search tree and convert the two-fork search tree into a sorted doubly linked list. Requires that no new nodes can be created, only the point pointer of the node in the tree can be adjusted.

Algorithm description

Using recursion, go to the left and right sub-tree of the current node into a doubly linked list, and then get the last element of the list on the left, the left pointer of the current element points to it, it points to the current element, the first element of the list on the right, its left pointer to the current element, the right pointer to the current element, Constantly looking from the left, find the first element and return a pointer to this element.

Summarize:
For this topic involving two forks, you can start with a test drive, write the test case first, and then encode it.

Code implementation
``#include <iostream>Using STD:: cout; using STD:: Cin; using STD:: Endl; struct TreeNode {int val; struct TreeNode*Left struct TreeNode*Right TreeNode (int x): Val (x), left (NULL), Right (NULL) {}};class Solution { Public: TreeNode*Convert (TreeNode*Prootoftree) {TreeNode*P=Prootoftree; TreeNode*Pl TreeNode*prif* 2!= NULL) {PL=Convert (P -left); pr=Convert (P -right); P -Right=prif(PR) {PR -Left=P } while(PL&&Pl -right) {PL=Pl -Right }if(PL) PL -Right=P P -Left=Pl while(p -left) {p=P -Left }          }returnP }};int Main () {TreeNode*P1= NewTreeNode (1); TreeNode*P2= NewTreeNode (2); TreeNode*P3= NewTreeNode (3); TreeNode*P4= NewTreeNode (4); TreeNode*P5= NewTreeNode (5); TreeNode*P6= NewTreeNode (6); TreeNode*P7= NewTreeNode (7); P4 -Left=P2; P4 -Right=P6; P2 -Left=P1; P2 -Right=P3; P6 -Left=P5; P6 -Right=P7;     Solution S; TreeNode*P=S.Convert (p4); while(p -right) {cout<<P -Val<<" "; P=P -Right } cout<<P -Val<<" "; cout<<"\ n"; while(p -left) {cout<<P -Val<<" "; P=P -Left } cout<<P -Val<<" ";}``

"Sword point offer" binary search tree and doubly linked list

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.