LeetCode #105 - Construct Binary Tree from Preorder and Inorder Traversal

题目描述:

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;
        }
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值