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

    解法:前序遍历的第一个元素为树根,因为树中无重复元素,因此遍历一遍可以在中序序列中找出树根所在位置,于是把中序序列分成前后两部分,分别为树根的左右子树。再递归调用重建左右子树即可。注意确定左右子树时中序序列和后序序列的两个下标值。rootIndex只能确定中序序列中左右子树的元素,而不能确定前序序列的左右子树元素位置,后者需要根据左右子树元素个数来确定:第一个为树根,接下来的leftLength个为左子树元素,最后rightLength个为右子树元素。

    /**
     * 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* buildTree(vector<int>& preorder, vector<int>& inorder) {
            int pn = preorder.size(), in = inorder.size();
            if (pn == 0 || in == 0 || pn != in) return NULL;
            return buildRecursion(preorder, 0, pn - 1, inorder, 0, in - 1);
        }
    private:
        TreeNode* buildRecursion(vector<int>& preorder, int pbeg, int pend, vector<int>& inorder, int ibeg, int iend) {
            TreeNode* root = new TreeNode(preorder[pbeg]);
            if (ibeg == iend) return root;
            int rootIndex = ibeg;
            while (rootIndex <= iend && inorder[rootIndex] != root->val)
                ++rootIndex;
            int leftLength = rootIndex - ibeg, rightLength = iend - rootIndex;
            if (leftLength > 0)
                root->left = buildRecursion(preorder, pbeg + 1, pbeg + leftLength, inorder, ibeg, rootIndex - 1);
            if (rightLength > 0)
                root->right = buildRecursion(preorder, pbeg + leftLength + 1, pend, inorder, rootIndex + 1, iend);
            return root;
        }
    };
  • 相关阅读:
    凸包模板
    1060E Sergey and Subway(思维题,dfs)
    1060D Social Circles(贪心)
    D
    牛客国庆集训派对Day2
    网络流
    Tarjan算法(缩点)
    莫队分块算法
    计算几何
    hdu5943素数间隙与二分匹配
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/5046148.html
Copyright © 2011-2022 走看看