1. 程式人生 > >LeetCode Week 5

LeetCode Week 5

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.

For example, given
在這裡插入圖片描述

solutions:

本題意是要求根據輸入的前序和中序遍歷來確定一顆唯一的二叉樹。

由前序遍歷的要求我們可知,前序遍歷的第一個元素一定是二叉樹的根,且題目說了陣列中無重複元素,由此我們可以在中序陣列中找到這個元素,並以此為分節點,左邊則是中序遍歷的左子樹,右邊則是中序遍歷的右子樹。之後便可根據中序的左右子樹確定前序遍歷的左右部分。接著遞迴左右子樹,最後得到一顆唯一的二叉樹。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildtree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }
    TreeNode* buildtree(vector<int>& preorder, int pleft, int pright, vector<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 *root = new TreeNode(preorder[pleft]);
        root->left = buildtree(preorder, pleft + 1, pleft + i - ileft, inorder, ileft, i - 1);
        root->right = buildtree(preorder, pleft + i - ileft + 1, pright, inorder, i + 1, iright);
        return root;
    }
};

在這裡插入圖片描述