forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
514006f
commit f38fc83
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
36 changes: 36 additions & 0 deletions
36
construct-binary-tree-from-preorder-and-inorder-traversal/imsosleepy.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// ํผ์์ ๋ชปํ์ด์ GPT์ ๋์์ ๋ฐ์ | ||
// ์ ๋ ๋ฐฐ์ด์ด ํ์ํ๊ฐ? | ||
// ์ ์ ์ํ(preorder): ํธ๋ฆฌ์ ๋ฃจํธ๋ฅผ ๊ฐ์ฅ ๋จผ์ ๋ฐฉ๋ฌธํฉ๋๋ค. ๊ทธ ํ ์ผ์ชฝ ์๋ธํธ๋ฆฌ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ๋ฐฉ๋ฌธํฉ๋๋ค. ํ์ง๋ง ์ด ์ ๋ณด๋ง์ผ๋ก๋ ๊ฐ ์๋ธํธ๋ฆฌ๊ฐ ์ด๋ ๋ถ๋ถ์ธ์ง, ๊ทธ๋ฆฌ๊ณ ๊ทธ ์๋ธํธ๋ฆฌ์ ๊ตฌ์ฒด์ ์ธ ๊ตฌ์ฑ ์์๊ฐ ๋ฌด์์ธ์ง๋ฅผ ์ ์ ์์ต๋๋ค. | ||
// | ||
// ์ค์ ์ํ(inorder): ํธ๋ฆฌ์ ์ผ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ๋จผ์ ๋ฐฉ๋ฌธํ๊ณ , ๋ฃจํธ๋ฅผ ๋ฐฉ๋ฌธํ ํ, ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ๋ฐฉ๋ฌธํฉ๋๋ค. ์ด ๋ฐฐ์ด์ ํตํด ๋ฃจํธ๊ฐ ํธ๋ฆฌ์ ์ด๋ ์์น์ ์๋์ง ํ์ธํ ์ ์์ต๋๋ค. ๋ฃจํธ์ ์์น๋ฅผ ์๋ฉด, ๊ทธ ์์น๋ฅผ ๊ธฐ์ค์ผ๋ก ์ผ์ชฝ๊ณผ ์ค๋ฅธ์ชฝ ์๋ธํธ๋ฆฌ๋ฅผ ๋๋ ์ ์์ต๋๋ค. | ||
|
||
// ํ ๋ฐฐ์ด๋ก๋ ํธ๋ฆฌ์ ๊ตฌ์กฐ๋ฅผ ๋ณต์ํ ์ ์๋ ์ด์ | ||
// ์ ์ ์ํ๋ง์ผ๋ก๋ ๊ฐ ๋ ธ๋์ ์ผ์ชฝ ์์์ธ์ง ์ค๋ฅธ์ชฝ ์์์ธ์ง ์ ์ ์์ต๋๋ค. ์๋ฅผ ๋ค์ด, [3, 9, 20, 15, 7]๋ผ๋ ์ ์ ์ํ ๋ฐฐ์ด๋ง ์๋ค๋ฉด, '9'๊ฐ 3์ ์ผ์ชฝ ์์์ธ์ง ์ค๋ฅธ์ชฝ ์์์ธ์ง ์ ์ ์์ต๋๋ค. | ||
// ์ค์ ์ํ๋ง์ผ๋ก๋ ํธ๋ฆฌ์ ๋ฃจํธ๋ฅผ ์ ์ ์์ผ๋ฏ๋ก, ๊ฐ ์๋ธํธ๋ฆฌ์ ๊ตฌ์ฒด์ ์ธ ๊ตฌ์กฐ๋ฅผ ์ ์ ์์ต๋๋ค. | ||
class Solution { | ||
public TreeNode buildTree(int[] preorder, int[] inorder) { | ||
return buildTreeHelper(preorder, inorder, 0, 0, inorder.length - 1); | ||
} | ||
|
||
private TreeNode buildTreeHelper(int[] preorder, int[] inorder, int preStart, int inStart, int inEnd) { | ||
if (inStart > inEnd) return null; | ||
|
||
int rootVal = preorder[preStart]; | ||
TreeNode root = new TreeNode(rootVal); | ||
|
||
int rootIndex = -1; | ||
for (int i = inStart; i <= inEnd; i++) { | ||
if (inorder[i] == rootVal) { | ||
rootIndex = i; | ||
break; | ||
} | ||
} | ||
|
||
int leftSize = rootIndex - inStart; | ||
root.left = buildTreeHelper(preorder, inorder, preStart + 1, inStart, rootIndex - 1); | ||
root.right = buildTreeHelper(preorder, inorder, preStart + leftSize + 1, rootIndex + 1, inEnd); | ||
|
||
return root; | ||
} | ||
|
||
} |