using System; using System.Collections.Generic; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 求二叉树的右视图 * @param preOrder int整型一维数组 先序遍历 * @param inOrder int整型一维数组 中序遍历 * @return int整型一维数组 */ List<int> preOrder; Dictionary<int, int> dicInOrder = new Dictionary<int, int>(); public List<int> solve (List<int> preOrder, List<int> inOrder) { List<int> res = new List<int>(); if(preOrder == null) return res; this.preOrder = preOrder; for(int i = 0; i < inOrder.Count; i++){ dicInOrder.Add(inOrder[i], i); } TreeNode root = solveGetTree(0, 0, preOrder.Count - 1); Queue<TreeNode> que = new Queue<TreeNode>(); que.Enqueue(root); while(que.Count != 0){ for(int i = que.Count; i > 0; i--){ TreeNode cur = que.Dequeue(); if(cur.left != null) que.Enqueue(cur.left); if(cur.right != null) que.Enqueue(cur.right); if(i == 1) res.Add(cur.val); } } return res; } public TreeNode solveGetTree(int root, int left, int right){ if(left > right) return null; TreeNode newNode = new TreeNode(preOrder[root]); int mid = dicInOrder[preOrder[root]]; newNode.left = solveGetTree(root + 1, left, mid - 1); newNode.right = solveGetTree(root + mid - left + 1, mid + 1, right); return newNode; } }