题意很简答,就是递归实现,直接参考代码吧。 查询index部分可以使用Map做查询,建议和下一道题 leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal 中后序构造BST和leetcode 449. Serialize and Deserialize BST 二叉搜索树BST的序列化和反序列化一起学习。 建议和leetcode 87. Scramble Strin...
node->right =bstFromPreorder(right);returnnode; } }; Github 同步地址: https://github.com/grandyang/leetcode/issues/1008 类似题目: Construct Binary Tree from Preorder and Postorder Traversal Construct Binary Tree from Inorder and Postorder Traversal Construct Binary Tree from Preorder and Inorder...
* preorder:root->left->right,so the first element of preorder array is the root of tree **/fun bstFromPreorder(preorder: IntArray): TreeNode?{if(preorder ==null||preorder.isEmpty()) {returnnull} val size=preorder.size val root= TreeNode(preorder[0])for(i in 1until size) { ...
*/privateclassSolution{privatevarhashTable:Dictionary<Int,Int>=[:]funcbuildTree(_inorder:[Int],_postorder:[Int])->TreeNode?{if(postorder.isEmpty){returnnil;}// 用在查询根节点 索引位置 相当于以空间换时间foriin0..<inorder.count{hashTable[inorder[i]]=i}returnbuild(inorder,0,inorder.count...
* };*/classSolution {public:voidbuildBST(TreeNode *&root,vector<int> &preorder,intpreBegin,intpreEnd,vector<int> &inorder,intinBegin,intinEnd) {if(preBegin>preEnd||inBegin>inEnd)return;intpRoot=preorder[preBegin]; root=newTreeNode(pRoot);intindex=0;for(inti=inBegin;i<=inEnd;i+...
Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume that duplicates do not exist in the tree. For example,