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

    题目:

    Given preorder and inorder traversal of a tree, construct the binary tree.

    思路:

    线序序列的第一个元素就是树根,然后在中序序列中找到这个元素(由于题目保证没有相同的元素,因此可以唯一找到),中序序列中这个元素的左边就是左子树的中序,右边就是右子树的中序,然后根据刚才中序序列中左右子树的元素个数可以在后序序列中找到左右子树的后序序列,然后递归的求解即可。

    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {number[]} preorder
     * @param {number[]} inorder
     * @return {TreeNode}
     */
    var buildTree = function(preorder, inorder) {
        if(preorder.length==0){
            return null;
        }
        return BuildTree(0,preorder.length-1,0,inorder.length-1,preorder,inorder);
    };
    
    function BuildTree(pStart,pEnd,iStart,iEnd,preorder,inorder){
        if(pStart==pEnd){
            return new TreeNode(preorder[pStart]);
        }
        if(pStart>pEnd){
            return null;
        }
        var rootval=preorder[pStart];
        var i=inorder.indexOf(rootval);
        var root=new TreeNode(rootval);
        root.left=BuildTree(pStart+1,pStart+(i-iStart),iStart,i-1,preorder,inorder);
        root.right=BuildTree(pStart+1+(i-iStart),pEnd,i+1,iEnd,preorder,inorder);
        return root;
    }
  • 相关阅读:
    C#中Post和Get提交
    C#实现动态页面静态化
    瀑布流的实现
    jQuery常用方法验证
    eclipse配置PHP开发环境
    数据结构学习
    机器学习实战
    Leetcode_StringToInteger
    网络学习
    leetcode_前期心得
  • 原文地址:https://www.cnblogs.com/shytong/p/5182846.html
Copyright © 2011-2022 走看看