Given preorder and inorder traversal of a tree, construct the binary tree.html
Note:
You may assume that duplicates do not exist in the tree.函數
這道題要求用先序和中序遍從來創建二叉樹,跟以前那道Construct Binary Tree from Inorder and Postorder Traversal 由中序和後序遍歷創建二叉樹原理基本相同,針對這道題,因爲先序的順序的第一個確定是根,因此原二叉樹的根節點能夠知道,題目中給了一個很關鍵的條件就是樹中沒有相同元素,有了這個條件咱們就能夠在中序遍歷中也定位出根節點的位置,並以根節點的位置將中序遍歷拆分爲左右兩個部分,分別對其遞歸調用原函數。代碼以下:post
/** * Definition for binary tree * 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 *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; } };
咱們下面來看一個例子, 某一二叉樹的中序和後序遍歷分別爲:ui
Preorder: 5 4 11 8 13 9url
Inorder: 11 4 5 13 8 9spa
5 4 11 8 13 9 => 5code
11 4 5 13 8 9 / \htm
4 11 8 13 9 => 5blog
11 4 13 8 9 / \遞歸
4 8
11 13 9 => 5
11 13 9 / \
4 8
/ / \
11 13 9
作完這道題後,大多人可能會有個疑問,怎麼沒有由先序和後序遍歷創建二叉樹呢,這是由於先序和後序遍歷不能惟一的肯定一個二叉樹,好比下面五棵樹:
1 preorder: 1 2 3
/ \ inorder: 2 1 3
2 3 postorder: 2 3 1
1 preorder: 1 2 3
/ inorder: 3 2 1
2 postorder: 3 2 1
/
3
1 preorder: 1 2 3
/ inorder: 2 3 1
2 postorder: 3 2 1
\
3
1 preorder: 1 2 3
\ inorder: 1 3 2
2 postorder: 3 2 1
/
3
1 preorder: 1 2 3
\ inorder: 1 2 3
2 postorder: 3 2 1
\
3
從上面咱們能夠看出,對於先序遍歷都爲1 2 3的五棵二叉樹,它們的中序遍歷都不相同,而它們的後序遍歷卻有相同的,因此只有和中序遍歷一塊兒才能惟一的肯定一棵二叉樹。