Construct Binary Tree from Preorder and Inorder Traversal

题目:根据中序遍历和前序遍历数组构建二叉树

解题思路:
比如 : pre = { A , B , D , E , C} in= {D , B , E , A , C}
1. A 为root, 在中序遍历中 , 找到左子树节点为D, B , E , 右子树 : C
2. A左子树根节点 = B , 同理找到它的左右子树…
3. 如此递归

/**
 * 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[] preorder, int[] inorder) {
        if(preorder.length == 0 || inorder.length == 0) return null;
        return build(preorder , 0 , preorder.length - 1 , inorder , 0 , inorder.length - 1);
    }

    public TreeNode build(int[] preorder , int ps , int pe , int[] inorder , int is , int ie ) {
        if(ps > pe) return null;

        TreeNode root = new TreeNode(preorder[ps]);
        int i = is;
        for(; i < inorder.length; i++) {
            if(inorder[i] == preorder[ps]) {
                break;
            }
        }

        root.left = build(preorder , ps+1 ,ps + i - is,inorder ,is ,i - 1);
        root.right = build(preorder,ps+i - is + 1 , pe, inorder , i+1 , ie);

        return root;
    }
}
发布了121 篇原创文章 · 获赞 2 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章