题目描述
对二叉树的节点来说,有本身的值域,有指向左孩子节点和右孩子节点的两个指针;对双向链表的节点来说,有本身的值域,有指向上一个节点和下一个节点的指针。在结构上,两种结构有相似性,现在有一棵搜索二叉树,请将其转换成一个有序的双向链表。
输入描述:
第一行一个数字 n 表示二叉树的总结点数。
以下 n 行每行三个整数 fa lch rch,表示节点 fa 的左儿子节点为 lch,右儿子节点为 rch。(若 lch 为 0 则表示 fa 没有左儿子,rch同理)
第一行的 fa 为根节点。
ps:节点的标号就是节点的值。
输出描述:
在给定的函数中返回双向链表的头指针。
示例1
输入
9
6 4 7
4 2 5
2 1 3
1 0 0
3 0 0
5 0 0
7 0 9
9 8 0
8 0 0
输出
1 2 3 4 5 6 7 8 9
解法一:递归
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
br.readLine();
TreeNode root = createTree(br);
root = changeToList(root);
StringBuilder sb = new StringBuilder();
while(root!=null){
sb.append(root.val+" ");
root = root.right;
}
System.out.println(sb.toString().trim());
}
public static TreeNode changeToList(TreeNode root){
if(root==null||(root.left==null&&root.right==null)) return root;
TreeNode left = root.left;
TreeNode right = root.right;
if(right!=null){
right = changeToList(right);
right.left = root;
root.right = right;
}
if(left!=null){
TreeNode llast = left;
while(llast.right!=null){
llast = llast.right;
}
left = changeToList(left);
llast.right = root;
root.left = llast;
return left;
}
return root;
}
//递归建树
public static TreeNode createTree(BufferedReader br){
try{
String[] arr = br.readLine().trim().split(" ");
int val = Integer.parseInt(arr[0]);
int l = Integer.parseInt(arr[1]);
int r = Integer.parseInt(arr[2]);
TreeNode node = new TreeNode(val);
if(l!=0){
node.left = createTree(br);
}
if(r!=0){
node.right = createTree(br);
}
return node;
}catch(Exception e){
return null;
}
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val){
this.val = val;
}
}
解法二:利用队列
public static TreeNode changeToList(TreeNode root){
if(root==null||(root.left==null&&root.right==null)) return root;
//利用队列
Queue<TreeNode> q = new LinkedList<>();
inOrderToQueue(root,q);
TreeNode pre = null;
root = q.peek();
while(!q.isEmpty()){
TreeNode tmp = q.poll();
tmp.left = pre;
if(pre!=null){
pre.right = tmp;
}
pre = tmp;
}
return root;
}
public static void inOrderToQueue(TreeNode root,Queue q){
if(root==null) return ;
inOrderToQueue(root.left,q);
q.offer(root);
inOrderToQueue(root.right,q);
}
解法三:再来个递归
public static TreeNode changeToList(TreeNode root){
if(root==null||(root.left==null&&root.right==null)) return root;
return process(root).start;
}
public static ResultType process(TreeNode root){
if(root==null){
return new ResultType(null,null);
}
ResultType left = process(root.left);
if(left.end!=null){
left.end.right = root;
}
root.left = left.end;
ResultType right = process(root.right);
if(right.start!=null){
right.start.left = root;
}
root.right = right.start;
return new ResultType(left.start==null?root:left.start,right.end==null?root:right.end);
}
class ResultType{
TreeNode start;
TreeNode end;
public ResultType(TreeNode start,TreeNode end){
this.start = start;
this.end = end;
}
}