Share my recursion solution


  • -1
    H

    Again,this port is very helpful.
    /**
    * Definition for a binary tree node.
    * public class TreeNode {
    * int val;
    * TreeNode left;
    * TreeNode right;
    * TreeNode(int x) { val = x; }
    * }
    */
    public class Solution {
    HashMap<Integer,Integer> hash = new HashMap<Integer, Integer>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
    for(int i=0; i<inorder.length;i++) hash.put(inorder[i],i);
    return helper(preorder,0,inorder,0,inorder.length-1);
    }
    public TreeNode helper(int[] preorder, int root, int[] inorder, int start, int end){
    if(root==preorder.length) return null;
    if(start>end) return null;

                int nodeval = preorder[root];
                TreeNode node = new TreeNode(nodeval);
                int index = hash.get(nodeval);
                node.left = helper(preorder,root+1,inorder,start, index-1);
                node.right = helper(preorder,root+(index-start)+1,inorder,index+1,end);
                return node;
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.