105. 从前序与中序遍历序列构造二叉树(深搜)

注意: 二叉树中没有重复元素,有重复元素就搞不出来了.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* root;
13     vector<int> Pre, In; //搞两个全局变量,这样调用函数的时候就不用传参了
14     TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
15         //pre:前序 in:中序
16         if (preorder.empty() || inorder.empty()) return 0;
17         Pre = preorder;
18         In = inorder;
19         build(0, Pre.size() - 1, 0, In.size() - 1, root);    
20         return root;
21     }
22     //build函数这个TreeNode*&引用很关键,不加这个&,函数栈里的root就只会传值,不会对原root进行修改
23     void build(int P1,int P2,int I1,int I2,TreeNode*& root) {
24         if (P1 > P2 || I1 > I2) return;
25         int P = 0, len = 0; //P存储数左右子树的父亲节点,len存储左子树的节点数
26         root = new TreeNode(Pre[P1]); //左右子树父亲节点
27         for (int i = I1; i <= I2; i++) {
28             if (In[i] == Pre[P1]) {
29                 P = i;  //找到左右子树的分割索引
30                 break;
31             }
32         }
33         if (In[P] != Pre[P1]) return;
34         len = P - I1;  //左子树的节点数
35         build(P1 + 1, P1 + len, I1, P - 1, root->left); //建立左子树
36         build(P1 + len + 1, P2, P + 1, I2, root->right);//建立右子树
37     }
38 };


猜你喜欢

转载自www.cnblogs.com/NiBosS/p/11963696.html