[leetcode] 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.

解題思路:
本題要求我們在給定二叉樹的前序遍歷數組和中序遍歷數組的情況下,構造二叉樹。基本思路如下:

  • 前序遍歷數組的第一個數preorder[0]就是二叉樹的根節點
  • 遍歷中序數組,找到根節點,假設為inorder[i]
  • 假定數組的長度為n, 則inorder[0]...inorder[i-1]構成左子樹,inorder[i+1]...inorder[n]構成右子樹。
  • 重復以上過程,即可構造二叉樹。

具體代碼如下:

class Solution {
public:
    TreeNode* buildTreeHelper(int preStart, int inStart, int inEnd, vector<int>& preorder, vector<int>& inorder)
    {
        if(preStart > preorder.size() -1 || inStart > inEnd) //右子樹為空的情況下,preStart == preorder.size() -1
            return NULL;
            
        int index = 0;
        TreeNode *root = new TreeNode(preorder[preStart]);
        for(int i = 0; i< inorder.size();++i)
        {
            if(inorder[i] == preorder[preStart])
                index = i;
        }
        
        root->left = buildTreeHelper(preStart + 1, inStart, index - 1, preorder,inorder);
        root->right = buildTreeHelper(preStart + index - inStart + 1, index + 1, inEnd, preorder,inorder); // 構造右子樹的時候,preStart,index,inStart都是數組中的絕對位置,preStart應該加上偏移量,因此為preStart + index - inStart + 1, preStart和inStart不一定相等
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildTreeHelper(0,0,inorder.size() -1,preorder,inorder);
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容