第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
输出两行整数分别表示按两种标准的边界节点。
16 1 1 2 3 2 0 4 4 7 8 7 0 0 8 0 11 11 13 14 13 0 0 14 0 0 3 5 6 5 9 10 10 0 0 9 12 0 12 15 16 15 0 0 16 0 0 6 0 0
1 2 4 7 11 13 14 15 16 12 10 6 3 1 2 4 7 13 14 15 16 10 6 3
import java.util.*;
class Node
{
int val;
Node left;
Node right;
public Node(int val)
{
this.val = val;
}
}
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int len = in.nextInt();
Node[] map = new Node[len + 1];
int root = in.nextInt();
map[root] = getNode(root);
for (int i = 2; i <= len; i++)
{
int parent = in.nextInt();
int l = in.nextInt();
int r = in.nextInt();
map[l] = getNode(l);
map[r] = getNode(r);
map[parent].left = map[l];
map[parent].right = map[r];
}
print1(map[root]);
print2(map[root]);
}
public static Node getNode(int i)
{
if (i < 1)
return null;
return new Node(i);
}
public static void print1(Node head)
{
if (head == null)
return;
int height = getHeight(head);
Node[][] map = new Node[height][2];
setMap(map, head, 0);
for (int i = 0; i < height; i ++)
{
System.out.print(map[i][0].val + " ");
}
printLeafNode(map, head, 0);
for (int i = height - 1; i >= 0; i--)
{
if (map[i][0] != map[i][1])
{
System.out.print(map[i][1].val + " ");
}
}
System.out.println();
}
public static void printLeafNode(Node[][] map, Node head, int k)
{
if (head == null)
return;
if (head != map[k][0]
&& head != map[k][1]
&& head.left == null
&& head.right == null)
{
System.out.print(head.val + " ");
}
else
{
printLeafNode(map, head.left, k + 1);
printLeafNode(map, head.right, k + 1);
}
}
public static void setMap(Node[][] map, Node head, int k)
{
if (head == null)
return;
map[k][0] = map[k][0] == null ? head : map[k][0];
map[k][1] = head;
setMap(map, head.left, k + 1);
setMap(map, head.right, k + 1);
}
public static int getHeight(Node head)
{
if (head == null)
return 0;
return 1 + Math.max(getHeight(head.left),
getHeight(head.right));
}
private static void print2(Node node)
{
if (node == null)
return;
System.out.print(node.val + " ");
if (node.left != null && node.right != null)
{
printLeft(node.left, true);
printRight(node.right, true);
}
else
{
print2(node.left == null ? node.right : node.left);
}
System.out.println();
}
private static void printRight(Node node, boolean print)
{
if (node == null)
return;
printRight(node.left, print && node.right == null);
printRight(node.right, print);
if (print || (node.left == null && node.right == null))
{
System.out.print(node.val + " ");
}
}
private static void printLeft(Node node, boolean print)
{
if (node == null)
return;
if (print || (node.left == null && node.right == null))
{
System.out.print(node.val + " ");
}
printLeft(node.left, print);
printLeft(node.right, print && node.left == null);
}
}