• 【树】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;
    }
  • 相关阅读:
    HTML表格的简单使用1
    守卫路由使用
    CSS高度塌陷问题解决方案
    CSS导航条nav简单样式
    Linux学习
    TYpeScript接口的使用
    javaScript中自定义sort中的比较函数,用于比较字符串长度,数值大小
    給eclipse添加字体,设置字体
    tomcat自动URLDecode解码问题(+号变空格)
    时间管理
  • 原文地址:https://www.cnblogs.com/shytong/p/5182846.html
Copyright © 2020-2023  润新知