zoukankan      html  css  js  c++  java
  • [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);
        }
    };
  • 相关阅读:
    管道流
    构造方法中用泛型
    代码实现长提闪烁
    关联事件,向窗体中添加控件,设置控件属性等系列操作
    picturebox中添加图片
    typeof gettype
    groupbox
    static用法
    运算符重载
    类修饰符
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3619883.html
Copyright © 2011-2022 走看看