1. 程式人生 > >105,從前序與中序遍歷序列構造二叉樹

105,從前序與中序遍歷序列構造二叉樹

根據一棵樹的前序遍歷與中序遍歷構造二叉樹。

注意: 你可以假設樹中沒有重複的元素。

例如,給出

前序遍歷 preorder = [3,9,20,15,7]
中序遍歷 inorder = [9,3,15,20,7]

返回如下的二叉樹:

    3
   / \
  9  20
    /  \
   15   7

思考:如何才能確定一棵樹? 結論:    通過中序遍歷和先序遍歷可以確定一個樹                 通過中序遍歷和後續遍歷可以確定一個樹                 通過先序遍歷和後序遍歷確定不了一個樹。 單獨先序遍歷:能求解根,但不能求解左子樹什麼時候結束、右子樹什麼時候開始。

根據先序和中序結果畫樹

演算法 1、通過先序遍歷找到根結點A,再通過A在中序遍歷的位置找出左子樹,右子樹 2、在A的左子樹中,找左子樹的根結點(在先序中找),轉步驟1 3、在A的右子樹中,找右子樹的根結點(在先序中找),轉步驟1

/**  * Definition for a binary tree node.  * public class TreeNode {  *     int val;  *     TreeNode left;  *     TreeNode right;  *     TreeNode(int x) { val = x; }  * }  */ class Solution {     public TreeNode buildTree(int[] preorder, int[] inorder) {          return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);     }      TreeNode buildTree(int[] preorder, int pLeft, int pRight, int[] inorder, int iLeft, int iRight) {         if (pLeft > pRight || iLeft > iRight) return null;         int i = 0;         for (i = iLeft; i <= iRight; ++i) {             if (preorder[pLeft] == inorder[i]) break;         }         TreeNode cur = new TreeNode(preorder[pLeft]);         cur.left = buildTree(preorder, pLeft + 1, pLeft + i - iLeft, inorder, iLeft, i - 1);         cur.right = buildTree(preorder, pLeft + i - iLeft + 1, pRight, inorder, i + 1, iRight);         return cur;     } }