import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; class TreeNode{ TreeNode left; TreeNode right; int val; public TreeNode(int val) { this.val = val; left = null; right = null; } } public class Main { public static Scanner sc = new Scanner(System.in); public static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); public static long mod = (long) Math.pow(2, 29); public static void main(String[] args) throws Exception { String line; String[] strArr; line = reader.readLine(); strArr = line.split(" "); int n = Integer.valueOf(strArr[0]); int rootVal = Integer.valueOf(strArr[1]); Map<Integer, TreeNode> mp = new HashMap<>(n); for (int i = 0; i < n; i++) { line = reader.readLine(); strArr = line.split(" "); int val = Integer.valueOf(strArr[0]); int leftVal = Integer.valueOf(strArr[1]); int rightVal = Integer.valueOf(strArr[2]); if (!mp.containsKey(val)) { mp.put(val, new TreeNode(val)); } if (leftVal != 0) { if (!mp.containsKey(leftVal)) { mp.put(leftVal, new TreeNode(leftVal)); } mp.get(val).left = mp.get(leftVal); } if (rightVal != 0) { if (!mp.containsKey(rightVal)) { mp.put(rightVal, new TreeNode(rightVal)); } mp.get(val).right = mp.get(rightVal); } } TreeNode root = mp.get(rootVal); inOrder(root); } // 左 根 右 static void inOrder(TreeNode root){ if(root == null){ return; } int v1 = 0; int v2 = 0; int lastVal = 0; TreeNode cur = root; while (cur != null){ if(cur.left == null){ // 打印 if(lastVal == 0){ lastVal = cur.val; }else { if(cur.val < lastVal){ // 有问题了 if(v1 == 0){ v1 = lastVal; v2 = cur.val; }else { v2 = cur.val; } } lastVal = cur.val; } cur = cur.right; }else { TreeNode pre = cur.left; while (pre.right != null && pre.right != cur){ pre = pre.right; } if(pre.right == null){ // 第一次访问 // 建立联系,并转向左节点 pre.right = cur; cur = cur.left; }else { // 第二次访问,表示cur的左子树都访问过了 // 打印 if(lastVal == 0){ lastVal = cur.val; }else { if(cur.val < lastVal){ // 有问题了 if(v1 == 0){ v1 = lastVal; v2 = cur.val; }else { v2 = cur.val; } } lastVal = cur.val; } pre.right = null; cur = cur.right; } } } System.out.println(Math.min(v1, v2) + " " + Math.max(v1, v2)); return; } } /* 3 1 1 2 3 2 0 0 3 0 0 1 2 */