Construct Binary Tree from Inorder and Postorder Traversal

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代码:

  1. TreeNode helper(int[] inorder,int ist,int[] postorder,int pst,int len) {
  2. if(len<1) return null;  //无左节点或者右节点
  3. if(len==1) {
  4. return new TreeNode(inorder[ist]);
  5. }
  6. int k = pst + len - 1;
  7. int tmp = postorder[k];
  8. int i=0;
  9. for(i=0;i<len;i++) {
  10. if(inorder[ist+i] == tmp) break;
  11. }
  12. TreeNode root = new TreeNode(inorder[ist+i]);
  13. root.left = helper(inorder,ist,postorder,pst,i);
  14. root.right = helper(inorder,ist+i+1,postorder,pst+i,len-1-i);  //len - 1 - i,已经处理一个节点了
  15. return root;
  16. }
  17. public TreeNode buildTree(int[] inorder, int[] postorder) {
  18. int ilen = inorder.length;
  19. int plen = postorder.length;
  20. if(ilen == 0) return null;
  21. if(ilen != plen) return null;
  22. return helper(inorder,0,postorder,0,ilen);
  23. }
posted @ 2014-07-26 10:57  purejade  阅读(76)  评论(0)    收藏  举报