标签:构造 init return efi code else color 不能 构造二叉树
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 11 //直接模拟 12 class Solution 13 { 14 public: 15 TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 16 { 17 int n = preorder.size(); 18 if(n == 0) return NULL; 19 return build(preorder,0,n - 1,inorder,0,n - 1); 20 } 21 22 TreeNode* build(vector<int>& preorder,int pb,int pe,vector<int>& inorder, int ib,int ie) 23 { 24 int val = preorder[pb]; 25 TreeNode* root = new TreeNode(val); 26 27 int i = ib; 28 for(;i <= ie;i ++) if(inorder[i] == val) break; 29 30 //有左子树就是i不能为ib 31 if(i != ib) root->left = build(preorder,pb + 1,pb + i - ib,inorder,ib,i - 1); 32 else root->left = 0; 33 34 //有右子树就是i不能为ie 35 if(i != ie) root->right= build(preorder,pb + i - ib + 1,pe,inorder,i + 1,ie); 36 else root->right = 0; 37 38 return root; 39 } 40 41 };
标签:构造 init return efi code else color 不能 构造二叉树
原文地址:https://www.cnblogs.com/yuhong1103/p/12558098.html