From 2fd4fe195e5f0d932441e0d360634917075972c4 Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Thu, 4 Jun 2020 08:52:10 +0800 Subject: [PATCH] =?UTF-8?q?Create=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9B=B8?= =?UTF-8?q?=E5=85=B3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Algorithm/剑指 Offer/二叉树相关.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 blogs/Algorithm/剑指 Offer/二叉树相关.md diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md new file mode 100644 index 0000000..18d0997 --- /dev/null +++ b/blogs/Algorithm/剑指 Offer/二叉树相关.md @@ -0,0 +1,35 @@ +--- +二叉树相关 +--- + +#### 目录 + +1. #### [07. 重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/) + +#### [07. 重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/) + +```java +class Solution { + + public TreeNode buildTree(int[] preorder, int[] inorder) { + int n = preorder.length; + if (n == 0) { + return null; + } + int rootVal = preorder[0], rootIndex = 0; + for (int i = 0; i < n; i++) { + if (inorder[i] == rootVal) { + rootIndex = i; + break; + } + } + TreeNode root = new TreeNode(rootVal); + root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1 + rootIndex), + Arrays.copyOfRange(inorder, 0, rootIndex)); + root.right = buildTree(Arrays.copyOfRange(preorder, 1 + rootIndex, n), + Arrays.copyOfRange(inorder, rootIndex + 1, n)); + return root; + } +} +``` +