[LeetCode]106 根据中序遍历和后序遍历构建二叉树

来源:互联网 发布:windows phone10更新 编辑:程序博客网 时间:2024/06/13 03:35

Construct Binary Tree from Inorder and Postorder Traversal(根据中序遍历和后序遍历构建二叉树)

【难度:Medium】
Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.
给定一棵二叉树的中序遍历和后序遍历,重构该二叉树。
假定二叉树中无重复值。


解题思路

根据题意,我们先来看一棵二叉树的中序遍历和后序遍历的结果:
这里写图片描述
中序遍历:6,4,7,2,5,1,8,3,9
后序遍历:6,7,4,5,2,8,9,3,1
由后序遍历的定义,我们知道最后一个值必定是二叉树的根节点root。由而中序遍历的定义,我们又可以发现根节点是左右子树的分界点。结合两者,就可以想到使用分治、递归的方法,由后序遍历来确定每一个根节点,然后在中序遍历中找到该节点的下标i,那么[start, i-1]就是该i节点的左子树,[i+1, end]就是该i节点的右子树,直到叶子节点的出现。
如第一趟遍历:
【6,4,7,2,5】,1,【8,3,9】
root节点: 1
左子树:【6,4,7,2,5】
右子树:【8,3,9】
再对左右子树执行相同方法即可。


c++代码如下:

/** * 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) {        if (inorder.empty() || postorder.empty())            return NULL;        int root_index = postorder.size()-1;        return createBST(inorder,postorder,0,root_index,root_index);    }    TreeNode* createBST(vector<int>& inorder, vector<int>& postorder, int start, int end, int& index) {        int v = postorder[index];        int i = end;        for (i; i >= start; i--)            if (inorder[i] == v)                break;        TreeNode* root = new TreeNode(v);        if (end >= i+1)            root->right = createBST(inorder,postorder,i+1,end,--index);        if (i-1 >= start)            root->left = createBST(inorder,postorder,start,i-1,--index);        return root;    }};
0 0
原创粉丝点击