美文网首页
105. Construct Binary Tree from

105. Construct Binary Tree from

作者: 7ccc099f4608 | 来源:发表于2020-07-05 23:49 被阅读0次

https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

image.png

(图片来源https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

日期 是否一次通过 comment
2020-07-05 0

Thoughts

  1. 前序:确定root;
  2. 中序:确定左、右子树的范围/长度

非递归

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);

        // 长度:delta = (inIndex - 1) - inStart + 1 = inIndex - inStart ;
        //      s = preStart + 1 + delta = preStart + inIndex - inStart + 1
        root.right = helper(preStart+inIndex-inStart+1, inIndex+1,
                inEnd, preOrder, inOrder);

        return root;
    }

相关文章

网友评论

      本文标题:105. Construct Binary Tree from

      本文链接:https://www.haomeiwen.com/subject/yqciqktx.html