1. 程式人生 > >LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和後序遍歷建立二叉樹 C++

LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和後序遍歷建立二叉樹 C++

範圍 leetcode lee bin 一個 truct span class div

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

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

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   /   9  20
    /     15   7

中序、後序遍歷得到二叉樹,可以知道每一次新數組的最後一個數為當時子樹的根節點,每次根據中序遍歷的根節點的左右兩邊確定左右子樹,再對應後序的左右子樹,不停遞歸得到根節點,可以建立二叉樹。每次由循環得到根節點在中序數組中坐標i

由中序遍歷知:每一次inorder的左子樹範圍[ileft,i-1],右子樹範圍[i+1,iright]

LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal 由中序和後序遍歷建立二叉樹 C++