V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hakunamatata11
V2EX  ›  推广

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

  •  
  •   hakunamatata11 · 2020-05-22 17:34:48 +08:00 · 683 次点击
    这是一个创建于 1464 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    在线评测地址: 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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1010 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:57 · PVG 06:57 · LAX 15:57 · JFK 18:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.