给定一个树的数组表示,按照前序,空节点用-1表示
例如vector<int> nums = {1,2,4,8,-1,-1,9,-1,-1,5,-1,-1,3,6,10,-1,-1,-1,7,-1,11,-1,-1}
算法如下:
input:
a[]
&i #as the current element in a[], reference data
root #the root pointer of tree
output:root of builded tree
def build_tree(root,a[],int i)
if(i>=a.size()) return
if(nums[i]<0){
i++;
return nullptr;
}else{
root = new TreeNode(nums[i]);
i++;
build_tree(root->left,a[],i);
build_tree(root->right,a[],i);
};
return root;
class A{ public: ///how to build a tree void showTree(TreeNode *root){ if(root){ cout<<root->val<<" "; showTree(root->left); showTree(root->right); } } void showTreeInorder(TreeNode *root){ if(root->left) showTreeInorder(root->left); cout<<root->val<<" "; if(root->right) showTreeInorder(root->right); } TreeNode *buildTree(TreeNode *p,vector<int> nums,int &i){ if(i>=(int)nums.size()) return nullptr;///对i值的控制要注意,决定递归结束.每一层i值都要前进一个,不管构建的是nullptr,还是TreeNode节点. if(nums[i]<0){///在nums数组范围内,如果当前值是-1,那么表示这是一个空节点 i++; p = nullptr; cout<<nums[i]<<endl;//也要输出,看到构建过程 }else{ p = new TreeNode(nums[i]);cout<<nums[i]<<"+"<<endl;///输出构建过程 i++; p->left = buildTree(p->left,nums,i); p->right = buildTree(p->right,nums,i); } return p; } TreeNode* buildTree(vector<int> &nums){ TreeNode *root = nullptr; int start = 0; root = buildTree(root,nums,start); return root; } void test(){ cout<<"begining"<<endl; vector<int> c = {1,2,4,8,-1,-1,9,-1,-1,5,-1,-1,3,6,10,-1,-1,-1,7,-1,11,-1,-1}; TreeNode *h = buildTree(c); showTree(h);cout<<endl; showTreeInorder(h);cout<<endl; cout<<"end"<<endl; } }; class TreeNode { public: int val; TreeNode *left; TreeNode *right; TreeNode(int x): val(x),left(nullptr),right(nullptr){} };