根据二叉树前序序列和中序序列构造二叉树

来源:互联网 发布:sql server2008教程 编辑:程序博客网 时间:2024/06/06 09:05
/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode buildTree(int[] preorder, int[] inorder) {        return build(preorder,0,preorder.length-1,inorder,0,preorder.length-1);         }    public TreeNode build(int[] preorder,int pres,int pree,int[]inorder,int ins,int ine){        if(pres>pree)            return null;        int root = preorder[pres];        int count =0;        for(int i=ins;i<ine;i++){            if(inorder[i]== root)                break;            else                count++;        }        TreeNode note = new TreeNode(root);        note.left = build(preorder,pres+1,pres+count,inorder,ins,ins+count-1);        note.right= build(preorder,pres+count+1,pree,inorder,ins+count+1,ine);        return note;    }}

阅读全文
0 0
原创粉丝点击