zoukankan      html  css  js  c++  java
  • leetcode Construct Binary Tree from Preorder and Inorder Traversal

    如果你没有做过根据中序遍历和后序遍历构造树,那么请先看Construct Binary Tree from Inorder and Postorder Traversal

    这题是:根据前序遍历和中序遍历构造树。

    类似上一题的思路,我们可以断定正确的是中序遍历的起始下标,和前序遍历左子树的起点下标,以及右子树结束下标。根据长度一致性,来确定未知的下标即可。不难吧。

    代码:              本文地址

    /**
     * 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 *fun106(vector<int> &preorder, int ps, int pe, vector<int> &inorder, int is, int ie)
        {
            if (ps > pe || is > ie) return NULL;
            TreeNode *root = new TreeNode(preorder[ps]);
            int rootval = root -> val, rootIndex;
        
            for (int i = 0; i <= ie; ++i)
            {
                if (inorder[i] == rootval)
                    rootIndex = i;
            }
        
            root -> left = fun106(preorder, ps + 1, rootIndex-1-is+ps+1,inorder, is, rootIndex - 1);
            root -> right = fun106(preorder, pe-(ie-(rootIndex+1)), pe, inorder, rootIndex + 1, ie);
        
            return root;
        }
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
        {
            if (preorder.size() == 0) return NULL;
            return fun106(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1);
        }
    };
  • 相关阅读:
    Selenium上传文件方法总结
    Maven安装配置
    selenium 3+java 配置全
    使用Eclipse创建Maven项目
    maven 学习
    解决Tomcatt下连接数据库的classNoFount问题
    Cookie的使用
    登录验证
    Servlet概述
    计算机科学学院静态网页
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4130791.html
Copyright © 2011-2022 走看看