Construct Binary Tree from Preorder and Inorder Traversal
程序员文章站
2022-06-18 17:46:37
...
解析: 思路类似根据中序和后序确定二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return DFS(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
TreeNode* DFS(vector<int>& preorder, int pleft, int pright,
vector<int>& inorder, int ileft, int iright){
if (pleft > pright || ileft > iright) return NULL;
int i = 0;
for (i = ileft; i <= iright; ++i){ //寻找二叉树的根节点,根据中序遍历划分左右子树
if (preorder[pleft] == inorder[i])
break;
}
TreeNode* cur = new TreeNode(preorder[pleft]);
//前序遍历:左子树的节点 pleft+1, pleft+i-ileft
//中序遍历:左子树的节点 ileft, i-1
cur->left = DFS(preorder, pleft+1, pleft+i-ileft, inorder, ileft, i-1);
//前序遍历:右子树的节点 pleft+i-ileft+1, pright
//中序遍历:右子树的节点 i+1, iright
cur->right = DFS(preorder, pleft+i-ileft+1, pright, inorder, i+1, iright);
return cur;
}
};
[1]https://www.cnblogs.com/grandyang/p/4296500.html?spm=a2c4e.10696291.0.0.6f5c19a4UVoRNo
上一篇: 将PPT2010幻灯片打包成CD或保存为视频解决异地无法播放问题
下一篇: 你看你像什么
推荐阅读
-
LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode: 105. Construct Binary Tree from Preorder and Inorder Traversal
-
leetcode 随笔 Construct Binary Tree from Preorder and Inorder Traversal
-
105. Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
算法系列——Binary Tree Preorder Traversal
-
Binary Tree Preorder Traversal
-
LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
-
中序遍历 94. Binary Tree Inorder Traversal