Wednesday, November 7, 2012

[LeetCode]Construct binary tree from inorder and postorder traversal

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

解题思路:
1. 从postorder里找到root node, 然后在inorder里找到此root node, 分别recursion

Java Code:

 public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder.length != postorder.length || postorder.length == 0) return null; 
           
          return buildSubTree(inorder, 0, inorder.length-1, postorder, 0, inorder.length-1);
        
    }
     
      public TreeNode buildSubTree(int[] inorder, int begin, int end, int[] postorder, int s, int t) {
        
           TreeNode root = new TreeNode(postorder[t]);
           int pos = begin;
           
           for(int i = begin; i <= end; i++){
               if(inorder[i] == postorder[t]){
                   pos = i;
                   break;
               }
           }
              
           if(begin <= pos - 1) root.left = buildSubTree1(inorder, begin, pos-1, postorder, s, s+pos-begin-1);
           
           if(pos+1 <= end) root.right = buildSubTree1(inorder, pos+1, end, postorder, s + pos-begin, t-1);
           
           return root;
    }

No comments:

Post a Comment