二叉樹 根據二叉樹的前序數組和中序序遍曆數組產生二叉樹,曆數二叉樹

來源:互聯網
上載者:User

二叉樹 根據二叉樹的前序數組和中序序遍曆數組產生二叉樹,曆數二叉樹

題目:給定二叉樹的前序走訪和中序遍曆,產生二叉樹。

Example:

前序走訪數組:preArr[]:{1,2,4,5,3,6,7}

中序遍曆數組:inArr[]:{4,2,5,1,6,3,7}

產生的二叉樹如:

解題思路:

由二叉樹的前序變數性質可知:preArr[0] 是數組的根節點,有根據二叉樹的中序遍曆的性質可知,{4,2,5}是二叉樹的左子樹,{6,3,7}在右子樹上,重複執行該操作就構造出了二叉樹

public class Solution {    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {        TreeNode root = new TreeNode(pre[0]);//前序的第一個數定為根        int len = pre.length;        //當只有一個數的時候        if (len == 1) {            root.left = null;            root.right = null;            return root;        }        //找到中序中的根位置        int rootval = root.val;        int i;        for (i = 0; i < len; i++) {            if (rootval == in[i])                break;        }        //建立左子樹        if (i > 0) {            int[] pr = new int[i];            int[] ino = new int[i];            for (int j = 0; j < i; j++) {                pr[j] = pre[j + 1];            }            for (int j = 0; j < i; j++) {                ino[j] = in[j];            }            root.left = reConstructBinaryTree(pr, ino);        } else {            root.left = null;        }        //建立右子樹        if (len - i - 1 > 0) {            int[] pr = new int[len - i - 1];            int[] ino = new int[len - i - 1];            for (int j = i + 1; j < len; j++) {                ino[j - i - 1] = in[j];                pr[j - i - 1] = pre[j];            }            root.right = reConstructBinaryTree(pr, ino);        } else {            root.right = null;        }        return root;    }    public static void main(String[] args) {        int[] preArr = {1, 2, 4, 5, 3, 6, 7};        int[] inArr = {4, 2, 5, 1, 6, 3, 7};        Solution s = new Solution();        TreeNode root = s.reConstructBinaryTree(preArr, inArr);        s.postOrder(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.