题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向
非递归
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
//非递归,根据前序遍历的特点,左<根<右
import java.util.Stack;
public class Solution {
public TreeNode Convert(TreeNode pRootOfTree) {
if(pRootOfTree == null)
return null;
Stack<TreeNode> stack = new Stack<TreeNode>(); //先进后出
TreeNode p = pRootOfTree;
TreeNode pre = null;// 用于保存挂链的位置,即每次挂完结点后的为尾结点
boolean isFirst = true;
while(p != null || !stack.isEmpty()){
while(p!=null){
stack.push(p);
p = p.left; //遍历完结点的左子树
}
p = stack.pop();
if(isFirst){
pRootOfTree = p;// 将中序遍历序列中的最左边即最小的结点记为pRootOfTree,也是链表的头结点
pre = pRootOfTree;
isFirst = false;
}else{ //挂链
pre.right = p;
p.left = pre;
pre = p;
}
p = p.right; //走右结点,如果右结点为null则出栈,回到p的父节点
}
return pRootOfTree;
}
}
递归
//递归,根据前序遍历的特点,左<根<右
public class Solution {
TreeNode head = null; //链表的头结点
TreeNode tail = null; //链表的尾结点
public TreeNode Convert(TreeNode pRootOfTree) {
bidirectionalLinkedList(pRootOfTree);
return head;
}
private void bidirectionalLinkedList(TreeNode pRootOfTree) {
if(pRootOfTree == null) return;
bidirectionalLinkedList(pRootOfTree.left); //递归遍历左结点
if (head == null) {
head = tail = pRootOfTree; //首尾结点都指向最小的结点
} else { //挂链
tail.right = pRootOfTree;
pRootOfTree.left = tail;
tail = pRootOfTree;
}
bidirectionalLinkedList(pRootOfTree.right);
}
}