【題目描述】輸入一棵二叉搜索樹,將該二叉搜索樹轉換成一個排序的雙向鏈表。要求不能創建任何新的結點,只能調整樹中結點指針的指向。
注:不能創建新的結點,理解爲不能顯式的new一個出來。
【解題思路】
//1. 利用中序遍歷的思想來完成。
//2. 給定一個指針用來存儲中序遍歷的第一個節點,作爲雙向鏈表的頭指針。
//3. 對於遍歷到的當前節點,若是第一個節點,則存儲起來。否則,將上一個節點的右指針指向當前節點,將當前節點的左指針指向上一個節點。同時將當前節點存儲爲上一個節點,並繼續遍歷。
//遞歸實現
public class Solution {
private TreeNode head; //中序遍歷中上一個節點
private TreeNode tail; //記錄中序遍歷中第一個節點,即鏈表的頭結點。
public TreeNode Convert(TreeNode pRootOfTree) {
inOrder(pRootOfTree);
return tail;
}
public void inOrder(TreeNode root){
if(root == null){
return;
}
if(root.left != null){
inOrder(root.left);
}
if(head == null){
head = root;
tail = root;
}else{
head.right = root;
root.left = head;
head = root;
}
if(root.right != null){
inOrder(root.right);
}
}
}
//非遞歸實現
import java.util.Stack;
public TreeNode ConvertBSTToBiList(TreeNode root) {
if(root==null)
return null;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
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){
root = p;// 將中序遍歷序列中的第一個節點記爲root
pre = root;
isFirst = false;
}else{
pre.right = p;
p.left = pre;
pre = p;
}
p = p.right;
}
return root;
}