由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 这道题如何得到最优解
相关主题
Construct Binary Tree from Preorder and Inorder Traversal算法复杂度?麻烦大家帮看看这段代码的问题
[leetcode] Binary Tree from Inorder & Postorder Traversal问一个构建二叉树的问题
这个inorder traversal 有错嘛,为什么leetcode 总报memory limit exceed?攒人品,amazon一面经历
大牛帮我看看这哪错了? iterative inorder traversalConstruct Binary Tree from Inorder and Postorder Traversal
inorder traversal的空间复杂度是O(N) 还是O(logN)?Amazon 电面
[合集] 微软面试的一道题讨论一道leetcode上面的题
F家phone interview的一道题狗店面,求BLESS
请教大家一个问题:Maximum Height (Depth) of a Binary Tree Using PreOrder Traversalleetcode里面的Recover Binary Search Tree怎么用O(1)space
相关话题的讨论汇总
话题: treenode话题: inorder话题: struct话题: int
进入JobHunting版参与讨论
1 (共1页)
w*******u
发帖数: 267
1
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-
inorder-traversal/
————————————————————————————————————
我的解法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder,
int inorderSize) {
if (preorderSize == 0) return NULL;
int rootVal = preorder[0];

int rootNodePos = -1;
for (int i = 0; i < inorderSize; i++) {
if (rootVal == inorder[i]) rootNodePos = i;
}

struct TreeNode *root = malloc(sizeof(struct TreeNode));
root->val = rootVal;
root->left = buildTree(preorder + 1, rootNodePos, inorder, rootNodePos);
root->right = buildTree(preorder + rootNodePos + 1, preorderSize -
rootNodePos - 1, inorder + rootNodePos + 1, inorderSize - rootNodePos - 1);
}
在leetcode上run了一下,要20ms,不是最优解。请问大虾们这道题如何得到最优解。谢
谢!!!
b***e
发帖数: 1419
2
你这个是O(n^2)的算法。想要吧复杂度降到O(n)的话要先hash sort一下in order
sequence。
1 (共1页)
进入JobHunting版参与讨论
相关主题
leetcode里面的Recover Binary Search Tree怎么用O(1)spaceinorder traversal的空间复杂度是O(N) 还是O(logN)?
问一个leetcode上Validate Binary Search Tree的问题[合集] 微软面试的一道题
讨论几道google题(附个人答案)F家phone interview的一道题
Find the node with given value in binary tree in in-order请教大家一个问题:Maximum Height (Depth) of a Binary Tree Using PreOrder Traversal
Construct Binary Tree from Preorder and Inorder Traversal算法复杂度?麻烦大家帮看看这段代码的问题
[leetcode] Binary Tree from Inorder & Postorder Traversal问一个构建二叉树的问题
这个inorder traversal 有错嘛,为什么leetcode 总报memory limit exceed?攒人品,amazon一面经历
大牛帮我看看这哪错了? iterative inorder traversalConstruct Binary Tree from Inorder and Postorder Traversal
相关话题的讨论汇总
话题: treenode话题: inorder话题: struct话题: int