106. Construct Binary Tree from Inorder and Postorder Traversal

来源:互联网 发布:php自动跳转页面 编辑:程序博客网 时间:2024/06/05 23:59

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


分析: 中序是左中右,后序是左右中,构建一棵树最重要的是找到其根节点,即中,因此以后序的最后一项开始遍历,然后以根节点的值在中序序列中寻找,若找到记录其位置,其位置左边的是当前根节点的左子树,其右边的则是其右子树。依次遍历即可。



code:

<span style="font-size:14px;">/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode buildTree(int[] inorder, int[] postorder) {        int m=inorder.length;        int n=postorder.length;        if(m!=n||m==0)            return null;        return treeHelp(inorder,postorder,0,m-1,0,n-1);                            }    public TreeNode treeHelp(int[] inorder,int[] postorder,int s1,int e1,int s2,int e2){        if(e2<s2)            return null;        TreeNode root=new TreeNode(postorder[e2]);        int i=e1;        for(;i>=s1;i--){            if(inorder[i]==postorder[e2])                break;        }        root.right=treeHelp(inorder,postorder,i+1,e1,e2-e1+i,e2-1);        root.left=treeHelp(inorder,postorder,s1,i-1,s2,e2-e1+i-1);        return root;            }}</span>


0 0
原创粉丝点击