From 82b16a00260076e4781f0b567ad6085c38d2385c Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Thu, 2 Jul 2020 09:29:44 +0800 Subject: [PATCH] =?UTF-8?q?Update=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 | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md index 18d0997..b78ff77 100644 --- a/blogs/Algorithm/剑指 Offer/二叉树相关.md +++ b/blogs/Algorithm/剑指 Offer/二叉树相关.md @@ -33,3 +33,35 @@ class Solution { } ``` +```java +class Solution { + + public TreeNode buildTree(int[] preorder, int[] inorder) { + if (preorder == null || preorder.length == 0) { + return null; + } + TreeNode root = new TreeNode(preorder[0]); + int length = preorder.length; + Stack stack = new Stack<>(); + stack.push(root); + int inorderIndex = 0; + for (int i = 1; i < length; i++) { + int preorderVal = preorder[i]; + TreeNode node = stack.peek(); + if (node.val != inorder[inorderIndex]) { + node.left = new TreeNode(preorderVal); + stack.push(node.left); + } else { + while (!stack.isEmpty() && stack.peek().val == inorder[inorderIndex]) { + node = stack.pop(); + inorderIndex++; + } + node.right = new TreeNode(preorderVal); + stack.push(node.right); + } + } + return root; + } +} +``` +