LeetCode #105

来源:互联网 发布:共轭矩阵 编辑:程序博客网 时间:2024/05/01 01:43

题目描述:

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

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

根据前序遍历和中序遍历构造二叉树。还是利用递归来解决,前序遍历的第一个元素即为二叉树的根节点,而在中序遍历中根节点的左边就是左子树的中序遍历,右边就是右子树的中序遍历。所以可以确定根节点,然后分别求出左子树的前序遍历、中序遍历和右子树的前序遍历和中序遍历,运用递归再分别构造左子树和右子树。同时要注意,如果二叉树有重复的值出现,那么在中序遍历中确定根节点就变得更加困难,不过在题目中已经排除了这种情况。

class Solution {public:    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {        if(inorder.empty()||preorder.empty()) return NULL;        else         {            int root_val=preorder[0];            int index=0;            for(int i=0;i<inorder.size();i++)            {                if(inorder[i]==root_val)                {                    index=i;                    break;                }            }                        TreeNode* root=new TreeNode(root_val);            vector<int> v1(preorder.begin()+1,preorder.begin()+1+index);            vector<int> v2(inorder.begin(),inorder.begin()+index);            root->left=buildTree(v1,v2);            vector<int> v3(preorder.begin()+1+index,preorder.end());            vector<int> v4(inorder.begin()+1+index,inorder.end());            root->right=buildTree(v3,v4);            return root;        }    }};



原创粉丝点击