Java实现-前序遍历和中序遍历构建二叉树

Java实现-前序遍历和中序遍历构建二叉树_第1张图片


/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
 
 
public class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // write your code here
        TreeNode root=null;
		root=preAndIn(preorder, inorder);
		return root;
    }
    private static TreeNode preAndIn(int []preorder,int []inorder){
		if(inorder.length==0&&preorder.length==0){
			return null;
		}
		int val=preorder[0];
		TreeNode root=new TreeNode(val);
		int index=0;
		for(int i=0;i


你可能感兴趣的:(斩杀LintCode,All,in,One,LintCode)