美文网首页程序员面试的那些小事数据结构和算法分析算法
《剑指offer》第6题(重建二叉树)的Java实现

《剑指offer》第6题(重建二叉树)的Java实现

作者: 工程师milter | 来源:发表于2017-02-07 09:20 被阅读379次

    自己写的,需要的朋友可以看看。题目内容是根据二叉树前序和中序遍历结果重建二叉树,假设树中元素各不相同。

    首先是定义的TreeNode类。

    public class TreeNode {
        public int value;
        public TreeNode left,right;
        public TreeNode(int value){
            this.value = value;
            this.left = null;
            this.right = null;
        }
    }
    

    下面是实现代码和测试用例。

    /**
     * Created by milter on 2017/2/7.
     */
    public class Reconstruct_Binary_Tree_offer6 {
        public static TreeNode reconstructBinaryTree(int[]p,int[]m){
            if(p==null||m==null||p.length != m.length||p.length==0)
                return null;
            return recusiveConstruct(p,0,p.length-1,m,0,m.length-1);
    
        }
    
        private static TreeNode recusiveConstruct(int[] p, int pStart,int pEnd,
                                                  int[] m,int mStart,int mEnd) {
            TreeNode head = new TreeNode(p[pStart]);
            if(pStart == pEnd)
                return head;
            int partition = 0;
            for(int i = mStart; i <= mEnd; i++){
                if(m[i] == p[pStart]){
                    partition = i;
                    break;
                }
            }
            if(partition - mStart > 0)
                head.left = recusiveConstruct(p,pStart+1,pStart+partition-mStart,
                        m,mStart,partition-1);
            if(mEnd - partition > 0)
                head.right = recusiveConstruct(p,pStart+partition-mStart+1,pEnd,
                        m,partition+1,mEnd);
            return head;
        }
    
        public static void main(String[] args) {
            int[] p ={1,2,4,7,3,5,6,8};
            int[] m ={4,7,2,1,5,3,8,6};
            TreeNode treeRoot = reconstructBinaryTree(p,m);
            testPreorder(treeRoot);
    
        }
    
        private static void testPreorder(TreeNode treeRoot) {
            if(treeRoot == null)
                return;
            System.out.println(treeRoot.value);
            testPreorder(treeRoot.left);
            testPreorder(treeRoot.right);
        }
    }
    
    

    相关文章

      网友评论

      • ShiroSora:哈哈,刚好昨天做了这道题,写了有点晦涩的解决方案,楼主这个是很易懂的方案
        工程师milter:看到网上有的Java解法要频繁复制数组,效率太低,就把自己的分享出来了。
        工程师milter:@ShiroSora 看的电子书。
        ShiroSora:不过现在网页上不是第四题吗,楼主是买实体书了?

      本文标题:《剑指offer》第6题(重建二叉树)的Java实现

      本文链接:https://www.haomeiwen.com/subject/yklpittx.html