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);
        }
    };
  • 相关阅读:
    C#学习笔记
    Visual Studio 快捷键
    java 8 中lambda表达式学习
    Spfa算法
    dijkstra算法
    topSort
    并查集--学习详解
    trie树--详解
    POJ1988 并查集的使用
    Mybatis的一级缓存和二级缓存
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3619883.html
Copyright © 2011-2022 走看看