Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int *pre = &preorder[0]; int *in = &inorder[0]; return build(pre, in, inorder.size()); } TreeNode *build(int *pre, int *in, int n) { if(n == 0) return nullptr; TreeNode *root = new TreeNode(pre[0]); int i = 0; for(; i<n; i++) { if(in[i] == pre[0]) break; } root->left = build(pre+1, in, i); root->right = build(pre+i+1, in+i+1, n-i-1); return root; }
相关推荐
java java_leetcode-105-construct-binary-tree-from-preorder-and-inorde
105.construct_binary_tree_from_preorder_and_inorder_traversal从前序
java java_leetcode-107-binary-tree-level-order-traversal
java java_leetcode-102-binary-tree-level-order-traversal
LeetCode上的题目“105-construct-binary-tree-from-preorder”要求参与者根据前序遍历的序列构建一棵二叉树。这对于理解二叉树的性质和前序遍历算法至关重要。 前序遍历是二叉树遍历方式之一,按照“根节点-左子树...
LeetCode是一个提供算法练习题目的平台,其中第105题“根据前序遍历构造二叉树”要求解者实现一个算法,根据给定的前序遍历序列还原出原始的二叉树结构。 二叉树的前序遍历序列是按先根节点、后左子树、再右子树的...
js-leetcode题解之106-construct-binary-tree-from-inorder LeetCode第106题要求我们通过中序和后序遍历结果来重构二叉树。在JavaScript中,这是一个常见的算法问题,涉及到树的构造和递归的使用。 首先,需要理解...
在解决LeetCode上的0094号问题“Binary Tree Inorder Traversal”时,C语言是实现算法的常用语言之一。该题目要求设计一个算法来遍历二叉树,并按照中序遍历的方式返回遍历的结果。这不仅需要理解中序遍历的原理,还...
root.right = buildTree(inorder[inorder_index + 1:], postorder) root.left = buildTree(inorder[:inorder_index], postorder) return root ``` 利用上面的递归函数,我们可以将给定的中序和后序遍历结果转化...
对于LeetCode上编号为144的题目“Binary Tree Preorder Traversal”,我们可以采用递归或非递归的方式来解决。 首先,递归方法是前序遍历实现中最直观的一种。在递归函数中,我们首先将根节点的值添加到结果数组中...
在编写Python代码解决LeetCode上144题时,我们可以通过递归或迭代的方式实现二叉树的前序遍历。 使用递归方法时,通常定义一个辅助函数,该函数接收当前节点作为参数。如果当前节点为空,则直接返回;否则,首先...
java java_leetcode-110-balanced-binary-tree
在LeetCode上,问题编号94的题目“Binary Tree Inorder Traversal”就是要求对给定的二叉树进行中序遍历,并返回遍历的结果。给定的二叉树用JavaScript对象来表示,每个节点的值为一个数字,节点结构包含值、左子...
通过LeetCode题解的这个文件“js-leetcode题解之107-binary-tree-level-order-traversal-ii.js”,我们可以学习如何使用JavaScript编写二叉树层序遍历的变种,以及如何处理和操作队列数据结构。
java java_leetcode-99-recover-binary-search-tree
java java_leetcode-114-flatten-binary-tree-to-linked-list
leetcode是全球知名的在线编程平台,提供各种编程题目的解法,供程序员学习和练习。本文将详细解读如何使用Python解决leetcode上的“二叉树的中序遍历”问题,题目编号为094。该题目的核心是要求开发者编写代码,对...
2. 在LeetCode平台上,问题编号107的题目是“Binary Tree Level Order Traversal II”,它要求对给定的二叉树进行反向层级遍历,即从最后一层到第一层的顺序输出节点值。 3. 反向层级遍历算法可以通过先进行正常的...
java java_leetcode-maximum-depth-of-binary-tree
java java_leetcode-111-minimum-depth-of-binary-tree