• Java for LeetCode 106 Construct Binary Tree from Inorder and Postorder Traversal


    Construct Binary Tree from Inorder and Postorder Traversal

    Total Accepted: 31041 Total Submissions: 115870

     
     

    Given inorder and postorder traversal of a tree, construct the binary tree.

    Note:
    You may assume that duplicates do not exist in the tree.

    解题思路:

    修改下上题代码解决,JAVA实现如下:

    	static public TreeNode buildTree(int[] inorder, int[] postorder) {
    		 return buildTree(postorder, inorder, 0, postorder.length-1, 0, inorder.length-1);  
        }  
        static public TreeNode buildTree(int[] postorder, int[] inorder, int pBegin, int pEnd, int iBegin, int iEnd){  
            if(pBegin>pEnd)  
                return null;  
            TreeNode root = new TreeNode(postorder[pEnd]);  
            int i = iBegin;  
            for(;i<iEnd;i++)
                if(inorder[i]==root.val)  
                    break;  
            int lenLeft = i-iBegin;  
            root.left = buildTree(postorder, inorder, pBegin, pBegin+lenLeft-1, iBegin, i-1);  
            root.right = buildTree(postorder, inorder, pBegin+lenLeft, pEnd-1, i+1, iEnd);  
            return root;
        }
    
  • 相关阅读:
    Java学习日报8..4
    Java学习日报8.3
    Java学习日报8.2
    Java学习日报7.31
    Java学习日报7.30
    Java学习日报7.29
    [标签] Java学习日报7.28
    Java学习日报7.27
    停更
    MG51--day5 I AM BACK/流水灯/数码管动态显示
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4524684.html
Copyright © 2020-2023  润新知