1. 程式人生 > >根據中序遍歷和後序遍歷樹構造二叉樹

根據中序遍歷和後序遍歷樹構造二叉樹

eno build 中序遍歷樹 oot post rsa uil cnblogs 找到

根據中序遍歷和後序遍歷樹構造二叉樹

樣例:

給出樹的中序遍歷: [1,2,3] 和後序遍歷: [1,3,2]

返回如下的樹:

2

/ \

1 3

借鑒上一篇《前序遍歷和中序遍歷樹構造二叉樹》,我們知道中序遍歷為左->中->右,後序遍歷為左->右->中。於是後序遍歷的最後一個值即為根節點的值,根據這個值我們在中序遍歷中找到根節點左子樹和右子樹的值,遞歸構造左子樹和右子樹即可。

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 
*/ class Solution { /** [email protected] inorder : A list of integers that inorder traversal of a tree [email protected] postorder : A list of integers that postorder traversal of a tree [email protected] : Root of a tree */ public: TreeNode *construct(vector<int
> &inorder, vector<int> &postorder, int is, int ie, int ps, int pe) { TreeNode * root = new TreeNode(postorder[pe]); if (ps == pe) return root; int i; for (i = 0; i < ie; i++) { if (inorder[i] == root->val) break
; } if (i-1 >= is) { root->left = construct(inorder, postorder, is, i-1, ps, ps+i-1-is); } if (i+1 <= ie) { root->right = construct(inorder, postorder, i+1, ie, ps+i-is, pe-1); } return root; } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { if (inorder.empty() || postorder.empty() || inorder.size() != postorder.size()) return NULL; return construct(inorder, postorder, 0, inorder.size()-1, 0, postorder.size()-1); } };

根據中序遍歷和後序遍歷樹構造二叉樹