题解 | #牛群的树形结构重建#
牛群的树形结构重建
https://www.nowcoder.com/practice/bcabc826e1664316b42797aff48e5153
题目考察的知识点是:
本题主要考察二叉树的遍历。
题目解答方法的文字分析:
先进行中序遍历,然后进行后序遍历最后得到结果。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param inOrder int整型一维数组 * @param postOrder int整型一维数组 * @return TreeNode类 */ public TreeNode buildTree (int[] inOrder, int[] postOrder) { // write code here if (inOrder.length == 0 && postOrder.length == 0) { return null; } int num = postOrder[postOrder.length - 1]; TreeNode head = new TreeNode(num); int count = 0; for (int i = 0; i < inOrder.length; i++) { if (inOrder[i] == num) break; count++; } int[] inOrderLeft = Arrays.copyOfRange(inOrder, 0, count); int[] inOrderRight = Arrays.copyOfRange(inOrder, count + 1, inOrder.length); int[] postOrderLeft = Arrays.copyOfRange(postOrder, 0, count); int[] postOrderRight = Arrays.copyOfRange(postOrder, count, inOrder.length - 1); TreeNode left = buildTree(inOrderLeft, postOrderLeft); TreeNode right = buildTree(inOrderRight, postOrderRight); head.left = left; head.right = right; return head; } }#题解#