1. 程式人生 > >根據前序和中序(後序和中序)遍歷構造樹 #演算法#

根據前序和中序(後序和中序)遍歷構造樹 #演算法#

原題如下

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

preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

思路

(1)前序序列的第一個元素一定是根節點; (2)中序序列中根節點左邊為左子樹的中序序列,右邊為右子樹的中序序列; (3)根據根節點在中序序列中的位置,又可在前序序列中得到左子樹的前序序列右子樹的前序序列; (4)用相同的原理又能分別找出左右子樹的根節點; (5)根節點的左子節點為左子樹的根節點,右子節點為右子樹的根節點; (6)再用相同的方法找出子節點的左右子節點;如此遞迴下去,直到最終序列為空。

程式碼

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    	if(preorder.empty()) return NULL;
    	int size = preorder.size();
    	int root_value = preorder[0];
        TreeNode* root = new TreeNode(root_value);
        vector<int> pre_left, in_left, pre_right, in_right;
        int i;
        for(i = 0; i < size; i++){
        	int value = inorder[i];
        	if(value == root_value) break;
        	in_left.push_back(value);
        	pre_left.push_back(preorder[i + 1]);
		}
		for(i++; i < size; i++){
			in_right.push_back(inorder[i]);
			pre_right.push_back(preorder[i]);
		}
        TreeNode* left = buildTree(pre_left, in_left);
        TreeNode* right = buildTree(pre_right, in_right);
        root->left = left;
        root->right = right;
        return root;
    }
};

後序和中序

思路類似,只不過根節點在postorder的末尾,程式碼如下:

class Solution {
public:
    TreeNode* buildTree(vector<int>& postorder, vector<int>& inorder) {
    	if(postorder.empty()) return NULL;
    	int size = postorder.size();
    	int root_value = postorder[size - 1]; // 這裡不同
        TreeNode* root = new TreeNode(root_value);
        vector<int> post_left, in_left, post_right, in_right;
        int i;
        for(i = 0; i < size; i++){
        	int value = inorder[i];
        	if(value == root_value) break;
        	in_left.push_back(value);
        	post_left.push_back(postorder[i]); // 這裡不同
		}
		for(i++; i < size; i++){
			in_right.push_back(inorder[i]);
			post_right.push_back(postorder[i - 1]); // 這裡不同
		}
        TreeNode* left = buildTree(post_left, in_left);
        TreeNode* right = buildTree(post_right, in_right);
        root->left = left;
        root->right = right;
        return root;
    }
};