zoukankan      html  css  js  c++  java
  • 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.

    For example, given
    
    preorder = [3,9,20,15,7]
    inorder = [9,3,15,20,7]
    Return the following binary tree:
    
        3
       / 
      9  20
        /  
       15   7
    

    思路还是比较简单的,在中序遍历中找前序遍历的值,然后递归

    /**
     * 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* dfs(vector<int>& preorder, vector<int>& inorder, int l, int r, int &num) {
            TreeNode* root = new TreeNode(preorder[num]);
            if (l > r) return nullptr;
            int p = l;
            while (p <= r && inorder[p] != preorder[num]) ++p;
            ++num;
            root->left = dfs(preorder, inorder, l, p-1, num);
            root->right = dfs(preorder, inorder, p+1, r, num);
            return root;
        }
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            int r = inorder.size() - 1;
            if (r == -1) return nullptr;
            int l = 0, num = 0;
            return dfs(preorder, inorder, l, r, num);
        }
    };
    
  • 相关阅读:
    [HAOI2008]糖果传递
    LGTB 与大数
    LGTB 与序列
    poj1160 Post Office
    组队
    [JLOI2015]装备购买
    三元组
    乘法表
    [BZOJ3730]震波
    [Luogu3345][ZJOI2015]幻想乡战略游戏
  • 原文地址:https://www.cnblogs.com/pk28/p/8654343.html
Copyright © 2011-2022 走看看