【每日一题】【递归】2021年12月24日-105. 从前序与中序遍历序列构造二叉树
给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
答案:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private Map<Integer, Integer> map; public TreeNode build(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) { //注意循环条件,先序的左边小于右边?--0个元素时,说明已经为空 if(preStart > preEnd) { return null; } int in_root = map.get(preorder[preStart]); int left_size = in_root - inStart; TreeNode root = new TreeNode(inorder[in_root]); root.left = build(preorder, preStart + 1, preStart + left_size, inorder, inStart, in_root - 1); //注意是preEnd,而不是in_root root.right = build(preorder, preStart + left_size + 1, preEnd, inorder, in_root + 1, inEnd); return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { map = new HashMap<>(); for(int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } return build(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); } }
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/15729432.html