zoukankan      html  css  js  c++  java
  • 106. Construct Binary Tree from Inorder and Postorder Traversal

        /*
         * 106. Construct Binary Tree from Inorder and Postorder Traversal
         * 11.21 By Mingyang 
         * Becuase k is not the length, it it need to -(inStart+1) to get the length
         * 需要注意的就是k不能作为postorder的index,必须加上距离才行
         */
        public TreeNode buildTree2(int[] inorder, int[] postorder) {
            int inStart = 0;
            int inEnd = inorder.length - 1;
            int postStart = 0;
            int postEnd = postorder.length - 1;
            return buildTree2(inorder, inStart, inEnd, postorder, postStart,postEnd);
        }
        public TreeNode buildTree2(int[] inorder, int inStart, int inEnd,int[] postorder, int postStart, int postEnd) {
            if (inStart > inEnd || postStart > postEnd)
                return null;
            int rootValue = postorder[postEnd];
            TreeNode root = new TreeNode(rootValue);
            int k = 0;
            for (int i = 0; i < inorder.length; i++) {
                if (inorder[i] == rootValue) {
                    k = i;
                    break;
                }
            }
            root.left = buildTree2(inorder, inStart, k - 1, postorder, postStart,
                    postStart + k - (inStart + 1));
            // Becuase k is not the length, it it need to -(inStart+1) to get the length
            //k只是与inorder有关,不能拿来postorder来用,这样就不行了
            root.right = buildTree2(inorder, k + 1, inEnd, postorder, postStart + k - inStart, postEnd - 1);
            // postStart+k-inStart = postStart+k-(inStart+1) +1
            return root;
        }
  • 相关阅读:
    java:产生小数位数为2的随机概率,使得和为1
    大数据网络分析规划
    java碎笔
    mysql修改记录
    mysql导入导出数据
    Centos中hive/hbase/hadoop/mysql实际操作及问题总结
    linux后台运行程序
    Centos搭建mysql/Hadoop/Hive/Hbase/Sqoop/Pig
    ARM-LINUX自动采集温湿度传感器数据
    java中枚举类型的使用
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5503923.html
Copyright © 2011-2022 走看看