Construct Binary Tree from Inorder and Postorder Traversal
程序员文章站
2022-04-27 11:35:32
...
解析:明显的递归类型题目,与前序遍历和中序遍历确定二叉树思路是一样的
后序遍历: 左 右 根
中序遍历: 左 根 右
1.根据后序遍历中的最后一个元素在中序遍历中确定根节点的位置,区分左右子树
2.建立当前节点的指针,并将该指针的左指针left指向左子树,右指针right指向右子树
利用i表示根节点的下标,ileft表示中序遍历的起点,iright表示中序遍历的终点,pleft表示后序遍历的起点,pright表示后序遍历的终点
左子树的区间:中序遍历[ileft,i-1],后序遍历[pleft, pleft+i-left-1] i-left表示左子树的节点个数
右子树的区间:中序遍历[i+1,iright],后序遍历[pleft+i-left, pright-1] i-left表示左子树的节点个数
/**
* 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>& inorder, vector<int>& postorder) {
return DFS(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
}
TreeNode* DFS(vector<int>& inorder, int ileft, int iright,
vector<int>& postorder, int pleft, int pright){
if (ileft > iright || pleft > pright) return NULL;
int i = 0;
for (i = ileft; i <= iright; ++i){ //在中序遍历序列中查找根
if (postorder[pright] == inorder[i])
break;
}
TreeNode* cur = new TreeNode(postorder[pright]);
cur->left = DFS(inorder, ileft, i-1, postorder, pleft, pleft+i-ileft-1);
cur->right = DFS(inorder, i+1, iright, postorder, pleft+i-ileft, pright-1);
return cur;
}
};
推荐阅读
-
Binary Tree Postorder Traversal
-
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
-
Given a binary tree, return the postorder traversal of its nodes' values.非递归后续遍历
-
LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
-
leetcode: binary-tree-postorder-traversal:后序遍历二叉树