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<<" ";}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Sword point offer" binary search tree and doubly linked list