zoukankan      html  css  js  c++  java
  • 复原二叉树

    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;
        }
    }
  • 相关阅读:
    处理跨浏览器的事件处理程序
    html5 canvas时钟
    拖拽事件的原理
    改变top使用轮播图
    程序开发之最大子数组
    第四周学习进度
    敏捷开发相关阅读
    构建之法读书笔记04
    四则运算终结版
    第三周学习进度
  • 原文地址:https://www.cnblogs.com/midiyu/p/8547923.html
Copyright © 2011-2022 走看看