105. Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:九头蛇算法 编辑:程序博客网 时间:2024/05/22 17:11

QUESTION

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

Note:

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

THINKING

考察数据结构的问题和#106类似,特别需要注意的是递归的时候传递参数的情况。如果作为参数传递的话,函数返回后,参数将保持不变。这是由于在进行递归时,参数被压入堆栈,在函数返回后取出,不会发生变化。在本题中,中序遍历的根节点是不会变化的,要依靠根节点把中序遍历分为两部分,所以适合作为参数。而preindex也就是先序遍历中的根节点要随着函数的调用向前遍历,所以不适合作为参数,所以把它作为全局变量。这样也有缺点,因为作为全局变量不安全也不专业,后面会给出改进的版本。

CODE
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int preIndex = 0;    public TreeNode buildTree(int[] preorder, int[] inorder) {        if(preorder.length == 0 || inorder.length == 0)            return null;        return creatTree(preorder,inorder,0,inorder.length - 1);    }    public TreeNode creatTree(int[] preorder,int[] inorder,int inStart,int inEnd){        int inIndex = 0;        if(inStart > inEnd || preIndex > preorder.length - 1)            return null;        TreeNode root = new TreeNode(preorder[preIndex++]);        if(inStart == inEnd)            return root;        for(int i = inStart;i <= inEnd;i++){            if(inorder[i] == root.val){                inIndex = i;                break;            }        }        root.left = creatTree(preorder,inorder,inStart,inIndex - 1);        root.right = creatTree(preorder,inorder,inIndex + 1,inEnd);        return root;    } }

二刷

public TreeNode buildTree(int[] preorder, int[] inorder) {    return helper(0, 0, inorder.length - 1, preorder, inorder);}public TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {    if (preStart > preorder.length - 1 || inStart > inEnd) {        return null;    }    TreeNode root = new TreeNode(preorder[preStart]);    int inIndex = 0; // Index of current root in inorder    for (int i = inStart; i <= inEnd; i++) {        if (inorder[i] == root.val) {            inIndex = i;        }    }    root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder);    root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);    return root;}
0 0