【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解題報告,leetcodepreorder

來源:互聯網
上載者:User

【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解題報告,leetcodepreorder

【原題】

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

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

【解析】

題意:根據二叉樹先序遍曆和中序遍曆的結果,構造二叉樹。跟 根據中序遍曆和後序遍曆結果構造二叉樹 類似。

先序遍曆:root - left - right,中序遍曆:left - root - right。

不同的是,先序遍曆的第一個元素就是根節點。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int[] preorder;    int[] inorder;        public TreeNode buildTree(int[] preorder, int[] inorder) {        if (preorder.length < 1 || inorder.length < 1) return null;        this.preorder = preorder;        this.inorder = inorder;        return getRoot(0, inorder.length - 1, 0);    }        // sub-tree range form begin to end in inorder[]    // rootpos refer the root postion in preorder[]    public TreeNode getRoot(int begin, int end, int rootpos) {        if (begin > end) return null;        TreeNode root = new TreeNode(preorder[rootpos]);        int i;        for (i = begin; i <= end; i++) {            if (inorder[i] == preorder[rootpos]) break;        }        // left part length: i - begin, right part length: end - i        root.left = getRoot(begin, i - 1, rootpos + 1);        root.right = getRoot(i + 1, end, rootpos + 1 + (i - begin));        return root;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.