## Sword refers to offer-binary search tree and doubly linked list

Topic description :

Input a binary search tree, convert the binary search tree into a sorted doubly linked list. It is required that no new nodes can be created, and only the point of the node pointer in the tree can be adjusted.

Analysis of ideas :

• Use the stack to do it, put the left subtree of the root node, the left subtree of the left subtree, ... all into the stack, and then the pop-up must be the minimum value
• Note that the leftmost one should be used as the head node and stored as a list
• As long as the stack is not empty, or the root still has a node, you can always connect
• The visited nodes are stored as pre, and the next cycle can be performed

Code :

import java.util.Stack;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}
}
*/
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null)
return null;
TreeNode root = pRootOfTree;
TreeNode pre = null,list = null;
Stack<TreeNode> s = new Stack<>();
while(root!=null || !s.isEmpty()){
while(root!=null){//Push stack, continuous left child nodes
s.push(root);
root = root.left;
}
root = s.pop();//The top of the stack is the leftmost node
if(list == null)//The first time that the leftmost node is the head node of the linked list
list = root;
if(pre != null){//Connect before and after
pre.right = root;
root.left = pre;
}
pre = root;//Record the last traversed node
root = root.right;
}
return list;
}
}

### Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324772256&siteId=291194637
Recommended
Ranking
Daily