• 复原二叉树


    1.由(preorder+inorder)复原

    /*
     * preorder:先序遍历数组
     * ps,pe:先序数组的首元素和末元素的索引
     * inod:中序遍历数组
     * is,ie:中序数组的首元素和末元素的索引 
     */
    public class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            return buildBT(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
        }
        
        private TreeNode buildBT(int[] preorder,int ps,int pe,int[] inorder,int is,int ie) {
            if(pe<ps)
                return null;
            TreeNode root=new TreeNode(preorder[ps]);
            if(pe==ps)
                return root;
            int middle=0;
            for(int i=is;i<=ie;i++)
                if(inorder[i]==preorder[ps]) {
                    middle=i;
                    break;
                }
            int len=middle-is;
            root.left=buildBT(preorder,ps+1,ps+len,inorder,is,middle-1);
            root.right=buildBT(preorder,ps+len+1,pe,inorder,middle+1,ie);
            return root;
        }
    }

    2.由(inorder+postorder)复原

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            return buildBT(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
        }
        
        private TreeNode buildBT(int[] inorder,int is,int ie,int[] postorder,int ps,int pe) {
            if(is>ie)
                return null;
            TreeNode root=new TreeNode(postorder[pe]);
            if(pe==ps)
                return root;
            int middle=0;
            for(int i=is;i<=ie;i++)
                if(inorder[i]==postorder[pe]) {
                    middle=i;
                    break;
                }
            int len=middle-is;
            root.left=buildBT(inorder,is,middle-1,postorder,ps,ps+len-1);
            root.right=buildBT(inorder,middle+1,ie,postorder,ps+len,pe-1);
            return root;
        }
    }
  • 相关阅读:
    C指针
    redis五种基本数据类型
    mongoDB MapReduce
    JSON传参
    mongodb查询实练
    逻辑数据结构和存储数据结构
    线性表的顺序存储和链式存储
    数据结构和算法关系
    UIActivityIndicatorView使用
    Swift中格式化日期
  • 原文地址:https://www.cnblogs.com/midiyu/p/8547923.html
Copyright © 2020-2023  润新知