1. 程式人生 > >Leetcode 106. 從中序與後序遍歷序列構造二叉樹 C++

Leetcode 106. 從中序與後序遍歷序列構造二叉樹 C++

題目描述在這裡插入圖片描述

思路

後序歷遍,最後一個元素就是根節點的元素,於是就可以找到這個根節點在中序歷遍中的位置,那麼左子樹的中序歷遍和右子樹的中序歷遍就可以知道。由此可以知道左子樹和右子樹的節點數量,進而可以在後序歷遍中確定左子樹的後序歷遍和右子樹的後序歷遍。之後,通過遞迴的思想,生成整棵樹。
注意:

  1. 在遞迴呼叫程式中最後使用四個變數來指示,分別是(1)中序歷遍的左端點,(2)中序歷遍的右端點,(3)後序歷遍的左端點,(4)後序歷遍的右端點。相反如果只用3個變數來確定,那麼思維過程很加大,很容易出錯,程式也會變得難以理解。

解答

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/* 以下程式碼中變數名的意義: 1.in_start 代表每一段中序歷遍的左端點 2.in_end 代表每一段中序歷遍的右端點 3.post_start 代表每一段後序歷遍的左端點 4.post_end 代表每一段後序歷遍的右端點 */ class Solution { public: TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return fun(inorder,postorder,0, inorder.size(), 0,postorder.
size()-1); } TreeNode* fun(vector<int>& inorder, vector<int>& postorder,int in_start, int in_end, int post_start, int post_end) { if(post_start==post_end) return new TreeNode(postorder[post_end]); if(post_start > post_end) return NULL; int root_value=
postorder[post_end]; TreeNode* root=new TreeNode(root_value); int i=0; for(;i<in_end;++i) { if(inorder[i]==root_value) break; } root->left=fun(inorder,postorder,in_start, i-1, post_start, post_start+ i-in_start-1); root->right=fun(inorder,postorder,i+1, in_end, post_start+i-in_start, post_end-1); return root; } };