LeetCode OJ 106. Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:知乎害人 编辑:程序博客网 时间:2024/06/02 03:10

LeetCode OJ 106. Construct Binary Tree from Inorder and Postorder Traversal


Description

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

解题思路

这道题跟题目105相似,只是前序遍历变成了后序遍历。根据二叉树的中序遍历和后序遍历构造二叉树。因为题目中提示了节点没有重复的值,所以我们可以判断节点的值来找出根节点。后序遍历的最后一个节点是当前子树的根节点,由此,我们可以找到根节点在中序便利中的位置root_i,把中序遍历分为两部分:这个根节点的左右子树的中序遍历。同时,后序遍历可以根据这个查找的偏移量root_i把前序遍历分为两部分:这个根节点的左右子树的后序遍历。这样就可以递归构造这个根节点的左右子树了。

Note:

vetctor容器中的assign()函数:
函数原型:

void assign(const_iterator first,const_iterator last);

void assign(size_type n,const T& x = T());

功能:

将区间[first,last)的元素赋值到当前的vector容器中,或者赋n个值为x的元素到vector容器中。注意是不含last这个元素的!这是cplusplus.com的说明链接

代码

个人github代码链接

/** * 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) {        TreeNode* root;        if(postorder.size() == 0 || inorder.size() == 0)            return NULL;        if(postorder.size() == 1)        {            root = new TreeNode(postorder[0]);            return root;        }        root = new TreeNode(postorder[postorder.size()-1]);        int root_i = 0;        vector<int>::iterator root_itr = inorder.begin();        for(root_itr; root_itr != inorder.end(); root_itr++){            if(root->val == (*root_itr)){                break;            }            root_i ++;        }        vector<int> left_post,right_post,left_in,right_in;        vector<int>::iterator itr = postorder.begin();        left_post.assign(itr, itr + root_i);        right_post.assign(itr + root_i, postorder.end() - 1);        itr = inorder.begin();        left_in.assign(itr,root_itr);        right_in.assign(root_itr + 1, inorder.end());        root->left = buildTree(left_in, left_post);        root->right = buildTree(right_in, right_post);        return root;    }};
0 0
原创粉丝点击