Construct Binary Tree from Inorder and Postorder Traversal --- LeetCode

来源:互联网 发布:linux snmp测试 编辑:程序博客网 时间:2024/06/05 10:10

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

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

解题思路:按着中序遍历序列和后序遍历序列构造二叉树。后序序列中的最后一个val值为根的val值。递归遍历如下:


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
     public  TreeNode  constructBTree(int[] inorder,int istart,int iend,int[] postorder,int pstart,int pend){
 int root=-1;
 TreeNode node=new TreeNode(postorder[pend]);
 for(int i=istart;i<=iend;i++){
      if(postorder[pend]==inorder[i]){
      root=i;
      break;
      }   
 }
 
 if(root>istart){
int len=root-istart;
node.left=constructBTree(inorder,istart,root-1,postorder,pstart,pstart+len-1); 
 }  
 if(root<iend){
int len=iend-root;
node.right=constructBTree(inorder,root+1,iend,postorder,pend-len,pend-1);  
 }
 return node;
}

    public TreeNode buildTree(int[] inorder, int[] postorder) {
     TreeNode root=null;
     int len=postorder.length;
 if(postorder==null||len==0){
 return null;
 }
     root=constructBTree(inorder,0,len-1,postorder,0,len-1);  
     return root;
}
 
}


0 0
原创粉丝点击