[LeetCode] Construct Binary Tree from Inorder and Pretorder 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.

Solution:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *build(vector<int> &preorder, vector<int> &inorder, int pre_start, int pre_end, int in_start, int in_end)
{
    if(pre_start > pre_end || in_start > in_end)
        return NULL;
    TreeNode *curRoot = new TreeNode(preorder[pre_start]);
    int rootIndex = -1;
    for(int i = in_start;i <= in_end;i++)
    {
        if(inorder[i] == preorder[pre_start])
        {
            rootIndex = i;
            break;
        }
    }
    if(rootIndex == -1) return NULL;
    int leftNum = rootIndex - in_start;
    curRoot -> left = build(preorder, inorder, pre_start + 1, pre_start + leftNum, in_start, rootIndex - 1);
    curRoot -> right = build(preorder, inorder, pre_start + leftNum + 1, pre_end, rootIndex + 1, in_end);
    return curRoot;
}

TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        return build(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
    }
};

 

转载于:https://www.cnblogs.com/changchengxiao/p/3619883.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值