[leetcode/lintcode 题解] 前序遍历和中序遍历树构造二叉树

2020-05-22 17:34:48 +08:00
 hakunamatata11

[题目描述] 根据前序遍历和中序遍历树构造二叉树.

在线评测地址: https://www.jiuzhang.com/solution/construct-binary-tree-from-preorder-and-inorder-traversal/?utm_source=sc-csdn-fks0522

[样例] 样例 1:

输入:[],[]
输出:{}
解释:
二叉树为空

样例 2:

输入:[2,1,3],[1,2,3]
输出:{2,1,3}
解释:
二叉树如下
  2
 / \
1   3

[题解]

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

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

前序的第一个为根,在中序中找到根的位置。 中序中根的左右两边即为左右子树的中序遍历。同时可知左子树的大小 size-left 。 前序中根接下来的 size-left 个是左子树的前序遍历。 由此可以递归处理左右子树。

public class Solution {
    private int findPosition(int[] arr, int start, int end, int key) {
        int i;
        for (i = start; i <= end; i++) {
            if (arr[i] == key) {
                return i;
            }
        }
        return -1;
    }

    private TreeNode myBuildTree(int[] inorder, int instart, int inend,
            int[] preorder, int prestart, int preend) {
        if (instart > inend) {
            return null;
        }

        TreeNode root = new TreeNode(preorder[prestart]);
        int position = findPosition(inorder, instart, inend, preorder[prestart]);

        root.left = myBuildTree(inorder, instart, position - 1,
                preorder, prestart + 1, prestart + position - instart);
        root.right = myBuildTree(inorder, position + 1, inend,
                preorder, position - inend + preend + 1, preend);
        return root;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (inorder.length != preorder.length) {
            return null;
        }
        return myBuildTree(inorder, 0, inorder.length - 1, preorder, 0, preorder.length - 1);
    }
}

[更多语言代码参考] https://www.lintcode.com/problem/construct-binary-tree-from-preorder-and-inorder-traversal/?utm_source=sc-csdn-fks0522

687 次点击
所在节点    推广
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/674458

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX