105. Construct Binary Tree from Preorder and Inorder Traversal

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

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

這種題目一看到就屬于完全無從下手的感覺,答案能看懂比較好理解,但是要自己想挺難。這類題應該是題量還沒上去,還沒產生模糊的“這類題大概是用這種思路、方法、模版來做”的大腦反應,還需要繼續多練題多總結。

Construct Tree from given Inorder and Preorder traversals

我們來看一下兩種樹的遍歷:
Inorder sequence: D B E A F C
Preorder sequence: A B D E C F

In a Preorder sequence, leftmost element is the root of the tree. So we know ‘A’ is root for given sequences. By searching ‘A’ in Inorder sequence, we can find out all elements on left side of ‘A’ are in left subtree and elements on right are in right subtree. So we know below structure now.

      A 
     / \
    /   \ 
 D B E   F C

We recursively follow above steps and get the following tree.

        A 
      /   \
     /     \
    B       C
   / \      / 
  /   \    /
 D     E  F

Algorithm: buildTree()

  1. Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below code) to pick next element in next recursive call.
  2. Create a new tree node tNode with the data as picked element.
  3. Find the picked element’s index in Inorder. Let the index be inIndex.
  4. Call buildTree for elements before inIndex and make the built tree as left subtree of tNode.
  5. Call buildTree for elements after inIndex and make the built tree as right subtree of tNode.6) return tNode.
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int preIndex = 0;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null){
            return null;
        }
        int len = preorder.length;
        return helper(preorder, inorder, 0,  len - 1);
    }
    
    private TreeNode helper(int[] preorder, int[] inorder, int start, int end){
        if (start > end){
            return null;
        }
        TreeNode tNode = new TreeNode(preorder[preIndex]);
        preIndex++;
        int inIndex = search(inorder, tNode.val, start, end);
        tNode.left = helper(preorder, inorder, start, inIndex - 1);
        tNode.right = helper(preorder, inorder, inIndex + 1, end);
        return tNode;
    }
    
    private int search(int[] inorder, int value, int start, int end){
        for (int i = start; i <= end; i++){
            if (inorder[i] == value){
                return i;
            }
        }
        return -1;
    }
    
    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 一大早,光線就明亮亮地晃眼睛,又是一個晴熱高溫日。 開車繞到西湖邊,停車一個山腳下,看到保俶塔的指示牌,原來是座寶...
    suzanneWH閱讀 274評論 0 1
  • 一輪彎月銀戈套, 春風粉蝶正好。 牧笛一曲忘塵囂。 無須揚鞭催,老牛慢犁田。 昨日少年鬢已白, 童顏不唱經年。 何...
    閻浮小學僧閱讀 782評論 1 0