【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.

有了先序和中序,基本思路就是递归的找左右子树的根节点,加入到树中
/**
 * 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 *root = NULL;  // 存储树的根节点
    // 递归函数,pre是先序,pl和pr为左或右子树的区间,in为中序,il和ir同为左或右子树的区间,sub决定是左子树还是右子树,par为父亲结点
    void fun(vector<int> &pre, int pl, int pr, vector<int> &in, int il, int ir, int sub, TreeNode *par) {
        if (pl <= pr) { // 左或右子树不为空
            TreeNode *tmp = new TreeNode(pre[pl]); // 新建一个结点,即某个子树的根节点
            if (root == NULL) {
                root = tmp; // 根节点
                par = root;
            } else {
                // 根据sub判断添加到左子树还是右子树
                if (sub == 0) par->left = tmp;
                if (sub == 1) par->right = tmp;
            }

            // 找到根节点在中序遍历中的位置
            int ipos = il;
            for (int i = il; i <= ir; ++i) {
                if (in[i] == pre[pl]) {
                    ipos = i;
                    break;
                }
            }

            // 找到先序遍历中左右子树的分隔位置
            int ppos = pl + ipos - il;

            // 递归构造左右子树
            if (ipos > il) fun(pre, pl+1, ppos, in, il, ipos-1, 0, tmp); // 有左子树
            if (ipos < ir) fun(pre, ppos+1, pr, in, ipos+1, ir, 1, tmp); // 有右子树
        }
    }    

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if (preorder.size() == 0) return NULL;
        //TreeNode *root = NULL;
        fun(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1, 0, NULL);
        return root;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值