Explore Enterprise Education Gitee Premium Gitee AI AI teammates
Fetch the repository succeeded.
Create your Gitee Account
Explore and code with more than 14 million developers,Free private repositories !:)
Sign up
Already have an account? Sign in
文件
master
Branches (1)
master
master
Branches (1)
master
Clone or Download
Clone/Download
Prompt
To download the code, please copy the following command and execute it in the terminal
To ensure that your submitted code identity is correctly recognized by Gitee, please execute the following command.
When using the SSH protocol for the first time to clone or push code, follow the prompts below to complete the SSH configuration.
1 Generate RSA keys.
2 Obtain the content of the RSA public key and configure it in SSH Public Keys
To use SVN on Gitee, please visit the usage guide
When using the HTTPS protocol, the command line will prompt for account and password verification as follows. For security reasons, Gitee recommends configure and use personal access tokens instead of login passwords for cloning, pushing, and other operations.
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # Private Token
master
Branches (1)
master
Java
/
DataStructures
/
Trees
/
CreateBinaryTreeFromInorderPreorder.java
Java
/
DataStructures
/
Trees
/
CreateBinaryTreeFromInorderPreorder.java
CreateBinaryTreeFromInorderPreorder.java 3.78 KB
Copy Edit Raw Blame History
package DataStructures.Trees;
import java.util.HashMap;
import java.util.Map;
import DataStructures.Trees.BinaryTree.Node;
/**
* Approach: Naive Solution: Create root node from first value present in
* preorder traversal. Look for the index of root node's value in inorder
* traversal. That will tell total nodes present in left subtree and right
* subtree. Based on that index create left and right subtree.
* Complexity:
* Time: O(n^2) for each node there is iteration to find index in inorder array
* Space: Stack size = O(height) = O(lg(n))
*
* Optimized Solution: Instead of iterating over inorder array to find index of
* root value, create a hashmap and find out the index of root value.
* Complexity:
* Time: O(n) hashmap reduced iteration to find index in inorder array
* Space: O(n) space taken by hashmap
*
*/
public class CreateBinaryTreeFromInorderPreorder {
public static void main(String[] args) {
test(new Integer[] {}, new Integer[] {}); // empty tree
test(new Integer[] { 1 }, new Integer[] { 1 }); // single node tree
test(new Integer[] { 1, 2, 3, 4 }, new Integer[] { 1, 2, 3, 4 }); // right skewed tree
test(new Integer[] { 1, 2, 3, 4 }, new Integer[] { 4, 3, 2, 1 }); // left skewed tree
test(new Integer[] { 3, 9, 20, 15, 7 }, new Integer[] { 9, 3, 15, 20, 7 }); // normal tree
}
private static void test(final Integer[] preorder, final Integer[] inorder) {
System.out.println("\n====================================================");
System.out.println("Naive Solution...");
BinaryTree root = new BinaryTree(createTree(preorder, inorder, 0, 0, inorder.length));
System.out.println("Preorder Traversal: ");
root.preOrder(root.getRoot());
System.out.println("\nInorder Traversal: ");
root.inOrder(root.getRoot());
System.out.println("\nPostOrder Traversal: ");
root.postOrder(root.getRoot());
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
BinaryTree optimizedRoot = new BinaryTree(createTreeOptimized(preorder, inorder, 0, 0, inorder.length, map));
System.out.println("\n\nOptimized solution...");
System.out.println("Preorder Traversal: ");
optimizedRoot.preOrder(root.getRoot());
System.out.println("\nInorder Traversal: ");
optimizedRoot.inOrder(root.getRoot());
System.out.println("\nPostOrder Traversal: ");
optimizedRoot.postOrder(root.getRoot());
}
private static Node createTree(final Integer[] preorder, final Integer[] inorder,
final int preStart, final int inStart, final int size) {
if (size == 0) {
return null;
}
Node root = new Node(preorder[preStart]);
int i = inStart;
while (preorder[preStart] != inorder[i]) {
i++;
}
int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1;
root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount);
root.right = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1,
rightNodesCount);
return root;
}
private static Node createTreeOptimized(final Integer[] preorder, final Integer[] inorder,
final int preStart, final int inStart, final int size,
final Map<Integer, Integer> inorderMap) {
if (size == 0) {
return null;
}
Node root = new Node(preorder[preStart]);
int i = inorderMap.get(preorder[preStart]);
int leftNodesCount = i - inStart;
int rightNodesCount = size - leftNodesCount - 1;
root.left = createTreeOptimized(preorder, inorder, preStart + 1, inStart,
leftNodesCount, inorderMap);
root.right = createTreeOptimized(preorder, inorder, preStart + leftNodesCount + 1,
i + 1, rightNodesCount, inorderMap);
return root;
}
}
Loading...
Report
Report success
We will send you the feedback within 2 working days through the letter!
Please fill in the reason for the report carefully. Provide as detailed a description as possible.
Please select a report type
Cancel
Send
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

Releases

No release

Contributors

All

Language(Optional)

Activities

can not load any more
Edit
About
Homepage
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/syysui/Java.git
git@gitee.com:syysui/Java.git
syysui
Java
Java
master
Going to Help Center

Search

Comment
Repository Report
Back to the top
Login prompt
This operation requires login to the code cloud account. Please log in before operating.
Go to login
No account. Register

AltStyle によって変換されたページ (->オリジナル) /